The tests exist to pin a decision: given this event, does the code reply, and with what? On this
box (no running Telegram) a test that needs the real transport is a test that hangs or lies.
This is the technique that got call-attendance-bot to 74 passed in 0.59s with zero sockets,
including five new regression tests for a spam bug.
Split what you are testing into three layers and fake only the last:
| Layer | Examples | What to do |
|---|---|---|
| Your own code | Config, parsers, command dispatch, is_admin() |
Keep real. Mocking these tests your mock, not your code. |
| The framework's input/output object | Telethon NewMessage.Event, PTB Update+Context |
Fake it — it carries your inputs and records your outputs. |
| The network client | TelegramClient, Application, httpx |
Never construct it. See §2. |
The whole test is then three lines: build the event → call the handler → read what it tried to send.
__init__Telegram constructors almost always create the client (TelegramClient(...),
Application.builder()...build()), which wants credentials, a session file and a socket. Bypass the
constructor and set only the attributes the method under test reads:
def _make_bot() -> CallAttendanceBot:
bot = object.__new__(CallAttendanceBot) # no client, no session file, no socket
bot.config = Config.from_env(_TEST_ENV) # real Config, dummy env values
bot._target_chat = "@mygroup"
bot._poll_seconds = 20
return bot
object.__new__(Cls) is the standard bypass — no __init__, no side effects. Monkeypatching
TelegramClient instead still imports the network stack and is more code.AttributeError: ... '_poll_seconds' — that is a signal to fix the fixture, not a reason to give
up and construct for real.Config.from_env({..., "ADMIN_IDS": "111"}))
so the parsing/defaults you actually ship stay under test, with no secret in the file.Implement only the members the production handler touches, and collect replies in a list so a test can assert on them:
class _FakeEvent:
def __init__(self, raw_text="", *, sender_id=_PLAIN_ID, is_private=True):
self.raw_text = raw_text
self.is_private = is_private
self._sender = _FakeSender(sender_id)
self.replies: list[str] = [] # ← the assertion surface
async def get_sender(self): return self._sender
async def reply(self, text, parse_mode=None): self.replies.append(text)
Starter you can copy straight into tests/: templates/fake-telegram-event.py (FakeSender +
FakeEvent, the make_instance(cls, **attrs) and run(coro) helpers, and three commented-out
example tests covering silence, rejection and execution).
raw_text, is_private, parse_mode).
A typo here raises AttributeError that reads exactly like a product bug.async wherever the real API is async. A sync stub fails only at the await site
(TypeError: object ... can't be used in 'await' expression) and looks like a bug in the handler.pytest-asyncio)If the suite does not already depend on pytest-asyncio, do not add it for one task — every new
dependency is a repo change you have to land and defend. Drive each test with the stdlib:
async def _handle(bot, event): # one-line adapter so tests read plainly
await bot._on_admin_message(event)
def test_command_from_admin_is_executed() -> None:
event = _FakeEvent("/start", sender_id=_ADMIN_ID)
asyncio.run(_handle(_make_bot(), event))
assert len(event.replies) == 1
asyncio.run per test gives each test a fresh event loop — at this size the cost is
microseconds, and the isolation is better than a shared session-scoped loop. If the suite already
uses pytest-asyncio, follow the suite: consistency beats the local preference.
«البوت يرد بس على الأوامر ويتجاهل أي رسالة عادية» is a negative requirement, and that is the common shape of spam/notification bugs. Prove the absence, not the absence of errors:
def test_plain_private_message_is_silently_ignored_non_admin() -> None:
event = _FakeEvent("أهلاً، عامل إيه؟", sender_id=_PLAIN_ID)
asyncio.run(_handle(_make_bot(), event))
assert event.replies == [] # a raised exception would fail too — this is the real claim
assert event.replies == [], never "it didn't raise". A handler that crashes and a handler
that returns early both "didn't reply" — only the recorder distinguishes them.test_plain_private_message_is_silently_ignored_admin), not for the method
(test_on_admin_message_1). The name is what a future reader greps.-v silently does nothingSome projects set addopts in pyproject.toml (typically -q), which neutralises your -v: you
get ..... and a total, grep for your test names returns nothing, and the run still says
"18 passed". Then "74 passed" is not evidence your five new tests exist — prove them by name:
uv run pytest tests/test_x.py -o addopts="" -v # ignore addopts for one run
uv run pytest -o addopts="" -v | grep -c PASSED # how many, by name
uv run pytest -o addopts="" -v | grep -E 'test_(plain|command)' # the ones YOU added
74 passed in 0.59s), not just dots.-v run (§6) — never inferred from the total.uv run ruff check . → All checks passed! — run lint even when the task never mentioned it; an
unlinted addition is a failed delivery on a repo that has a config.git show --stat HEAD lists only the files you meant to land: running the suite itself
generates uv.lock and caches (commit-landing-discipline §3b).pytest-asyncio, pytest-mock) unless the suite
already uses it.== [].git add -A right after running the suite — uv run just wrote a lockfile.pytest -v producing no test names is an addopts problem, not a pytest problem (§6).ad-hoc-verification.fullstack-functional-qa.e2e, app-lab.commit-landing-discipline.telegram-bot-ops §9 — that is
integration; this skill is the unit layer beneath it.