---
name: python-unit-testing
description: >-
  Write unit tests for Sohail's Python projects that run in under a second with zero network and zero
  plugin installs — faking the framework's event object instead of the framework, building the class
  under test without its network-creating `__init__`, driving async handlers from plain pytest when
  `pytest-asyncio` is not a dependency, and asserting SILENCE (`replies == []`) when the requirement
  is "reply only to X / ignore everything else". Use when a task says «ضيف اختبارات» / "add tests" /
  "احفظ السلوك ده باختبار", when a bug report needs a regression test, when a review pass asks for
  coverage of a handler, when constructing the class would open Telegram/HTTP/DB, or when `pytest -v`
  seems to hide your test names while the total still goes up.
license: MIT
compatibility: Requires pytest in the project (uv where the project uses it). Deliberately needs NO
  pytest-asyncio, NO pytest-mock, NO network and NO credentials.
metadata:
  version: 0.1.0
---

# Unit tests for Sohail's Python projects — no network, no plugins

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.

## 1. Test the branch, not the transport

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.

## 2. Build the class without running `__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:

```python
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.
- **Set exactly what the code path reads.** If you miss one you get
  `AttributeError: ... '_poll_seconds'` — that is a signal to fix the fixture, not a reason to give
  up and construct for real.
- Build the real value object from a **dummy** env dict (`Config.from_env({..., "ADMIN_IDS": "111"})`)
  so the parsing/defaults you actually ship stay under test, with no secret in the file.

## 3. The fake event records instead of sending

Implement only the members the production handler touches, and **collect replies in a list** so a
test can assert on them:

```python
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).

- **Copy the exact names the production code reads** (`raw_text`, `is_private`, `parse_mode`).
  A typo here raises `AttributeError` that reads exactly like a product bug.
- **Fake it `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.
- Add a member the moment the handler starts calling it — the fake grows with the code under test.

## 4. Async handlers from plain pytest (no `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:

```python
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.

## 5. Asserting silence — the requirement is often "don't do X"

«البوت يرد بس على الأوامر ويتجاهل أي رسالة عادية» is a **negative** requirement, and that is the
common shape of spam/notification bugs. Prove the absence, not the absence of errors:

```python
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.
- **Cover the mirror case.** The spam bug only bit on one side (non-admin senders), so also test the
  same plain message *from an admin*. One-sided coverage can pass on the broken code.
- **One test per branch, named for the behaviour**
  (`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.
- Boundary cases are nearly free: wrong chat scope (non-private), empty text, a command with no args.

## 6. Reading the output — when `-v` silently does nothing

Some 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:

```bash
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
```

## 7. Definition of done

1. Full suite green, and you have seen the **total count** (`74 passed in 0.59s`), not just dots.
2. Your new tests appear **by name** in a `-v` run (§6) — never inferred from the total.
3. `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.
4. `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).
5. *(When you claim "this bug is fixed")* — optionally revert the fix and watch the new test go red
   once, so you know the test can actually fail. Skip it only if you can say why.

## Pitfalls

- 🚫 **Do not stand up a real client "just to construct the object."** It needs credentials, a
  session file and network: it will hang the suite, and on a repo with a live session it can touch
  production.
- 🚫 **Do not add a dependency for one test task** (`pytest-asyncio`, `pytest-mock`) unless the suite
  already uses it.
- 🚫 **Do not mock your own code.** Value objects and predicates stay real; only the framework edge
  is fake.
- 🚫 **Do not settle for "no exception raised"** when the requirement is silence — assert `== []`.
- 🚫 **Do not `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).
- ⚠️ **A green suite after your fix is not proof the test targets the bug** — see DoD 5.

## Where this sits next to the others

- **Proving a change works in a repo with no test suite at all** → `ad-hoc-verification`.
- **Full-stack functional QA, API sweeps, DB persistence checks** → `fullstack-functional-qa`.
- **Browser/UI, Playwright, mobile** → `e2e`, `app-lab`.
- **Getting the commit cleanly onto origin** → `commit-landing-discipline`.
- **Harnesses inside the *deployed* bot (needs a live container)** → `telegram-bot-ops` §9 — that is
  integration; this skill is the unit layer beneath it.
