Files
overub/core/testing.py
2025-12-21 17:12:32 +01:00

81 lines
2.5 KiB
Python

from dataclasses import dataclass, field
from typing import Any, Callable, Optional
@dataclass
class MockUser:
id: int
@dataclass
class MockMessage:
raw_text: str = ""
replies: list[str] = field(default_factory=list)
reply_text: Optional[str] = None
async def reply(self, text: str) -> None:
self.replies.append(text)
self.reply_text = text
class MockEvent:
def __init__(self, text: str = "", sender_id: int = 0, chat_id: int = 0) -> None:
self.message = MockMessage(raw_text=text)
self.sender_id = sender_id
self.chat_id = chat_id
self.out = False
async def reply(self, text: str) -> None:
await self.message.reply(text)
self.reply_text = text
class PluginTest:
def __init__(self, app: Any = None, plugin_name: str = "") -> None:
self.app = app
self.plugin_name = plugin_name
async def test_command(
self,
command: str | Callable[..., Any],
args: Optional[list[str]] = None,
event: Optional[Any] = None,
) -> Any:
args = args or []
if callable(command):
handler = command
else:
if not self.app:
raise RuntimeError("App required for command lookup")
cmd = self.app.commands.get(command)
if not cmd:
raise RuntimeError("Command not found")
handler = cmd.handler
event = event or MockEvent()
await handler(event, args)
return event
async def test_events(self, event_name: str, payload: Optional[dict] = None) -> Any:
if not self.app:
raise RuntimeError("App required for event dispatch")
payload = payload or {}
return await self.app.events.emit(event_name, **payload)
async def test_database(self, key: str = "test", value: Any = None) -> Any:
if not self.app or not self.plugin_name:
raise RuntimeError("App and plugin_name required")
db = self.app.database.plugin_db(self.plugin_name)
await db.set(key, value)
return await db.get(key)
async def mock_message(self, text: str = "") -> Any:
return MockMessage(raw_text=text)
async def mock_user(self, user_id: int) -> Any:
return MockUser(id=user_id)
async def assert_reply(self, event: Any, expected: str) -> None:
actual = getattr(event, "reply_text", None)
if actual != expected:
raise AssertionError(f"Expected '{expected}', got '{actual}'")