aiogram_bot_tester 2.0.0__tar.gz → 2.2.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: aiogram_bot_tester
3
- Version: 2.0.0
3
+ Version: 2.2.0
4
4
  Summary: Test your Telegram bots easily
5
5
  Classifier: Programming Language :: Python :: 3
6
6
  Classifier: Operating System :: OS Independent
@@ -15,6 +15,8 @@ Description-Content-Type: text/markdown
15
15
 
16
16
  # aiogram_bot_tester
17
17
 
18
+ > Your missing test toolkit for Telegram bots.
19
+
18
20
  ![aiogram](https://img.shields.io/badge/aiogram-3.x-blue?logo=telegram)
19
21
  ![telegram](https://img.shields.io/badge/telegram-bot-blue?logo=telegram)
20
22
  ![status](https://img.shields.io/badge/status-WIP-orange)
@@ -46,6 +48,15 @@ pip install git+https://github.com/samedit66/aiogram-bot-tester.git
46
48
 
47
49
  `aiogram_bot_tester` is a lightweight way to test aiogram bots offline, without real Telegram API calls. It helps you simulate updates, check bot responses, and keep tests deterministic, so bot logic can be covered with confidence even when the conversation flow is complex.
48
50
 
51
+ ## Features
52
+
53
+ - **Fully offline testing** — run bot scenarios without a Telegram token, network requests, or real API calls.
54
+ - **Real aiogram pipeline** — updates pass through the actual dispatcher, routers, filters, middleware, and FSM machinery.
55
+ - **Conversation-first API** — send messages and commands, start the bot, and tap reply or callback buttons by their visible labels.
56
+ - **Readable assertions** — check message text, regular expressions, buttons, callback data, URLs, and complete keyboard layouts.
57
+ - **FSM support** — assert the current state and inspect FSM data across multi-step conversation flows.
58
+ - **Flexible test setup** — build a tester from reusable routers or an existing dispatcher, pass fake dependencies directly, and attach middleware when needed.
59
+
49
60
  ## Quick example
50
61
 
51
62
  ```python
@@ -1,5 +1,7 @@
1
1
  # aiogram_bot_tester
2
2
 
3
+ > Your missing test toolkit for Telegram bots.
4
+
3
5
  ![aiogram](https://img.shields.io/badge/aiogram-3.x-blue?logo=telegram)
4
6
  ![telegram](https://img.shields.io/badge/telegram-bot-blue?logo=telegram)
5
7
  ![status](https://img.shields.io/badge/status-WIP-orange)
@@ -31,6 +33,15 @@ pip install git+https://github.com/samedit66/aiogram-bot-tester.git
31
33
 
32
34
  `aiogram_bot_tester` is a lightweight way to test aiogram bots offline, without real Telegram API calls. It helps you simulate updates, check bot responses, and keep tests deterministic, so bot logic can be covered with confidence even when the conversation flow is complex.
33
35
 
36
+ ## Features
37
+
38
+ - **Fully offline testing** — run bot scenarios without a Telegram token, network requests, or real API calls.
39
+ - **Real aiogram pipeline** — updates pass through the actual dispatcher, routers, filters, middleware, and FSM machinery.
40
+ - **Conversation-first API** — send messages and commands, start the bot, and tap reply or callback buttons by their visible labels.
41
+ - **Readable assertions** — check message text, regular expressions, buttons, callback data, URLs, and complete keyboard layouts.
42
+ - **FSM support** — assert the current state and inspect FSM data across multi-step conversation flows.
43
+ - **Flexible test setup** — build a tester from reusable routers or an existing dispatcher, pass fake dependencies directly, and attach middleware when needed.
44
+
34
45
  ## Quick example
35
46
 
36
47
  ```python
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "aiogram_bot_tester"
3
- version = "2.0.0"
3
+ version = "2.2.0"
4
4
  description = "Test your Telegram bots easily"
5
5
  readme = "README.md"
6
6
  requires-python = ">=3.10"
@@ -6,6 +6,7 @@ import dataclasses as dc
6
6
  import datetime as dt
7
7
  import itertools
8
8
  import unittest.mock as mock
9
+ from collections.abc import Mapping
9
10
  from typing import Any, Iterator
10
11
 
11
12
  import aiogram as aio
@@ -15,6 +16,7 @@ import aiogram.fsm.storage.memory as fsm_memory
15
16
  import aiogram.methods as aio_methods
16
17
  import aiogram.types as aio_types
17
18
  from aiogram.client.session import aiohttp
19
+ from aiogram.dispatcher.middlewares.base import BaseMiddleware
18
20
 
19
21
  import aiogram_bot_tester.exceptions as abt_exceptions
20
22
  import aiogram_bot_tester.types as abt_types
@@ -249,17 +251,73 @@ class BotTester:
249
251
  """A bot functionality tester."""
250
252
 
251
253
  bot_conversation: BotConversation
252
- command_prefix: str = "/"
253
254
 
254
255
  @classmethod
255
256
  def from_dispatcher(cls, dispatcher: aio.Dispatcher, **kwargs: Any) -> BotTester:
256
- command_prefix = kwargs.pop("command_prefix", "/")
257
+ """Create a tester from an already configured dispatcher.
258
+
259
+ Args:
260
+ dispatcher: Configured aiogram dispatcher used to process test updates.
261
+ **kwargs: Arguments forwarded to :class:`BotConversation`.
262
+
263
+ Example:
264
+
265
+ ```python
266
+ from aiogram import Dispatcher
267
+ from aiogram_bot_tester import BotTester
268
+
269
+ dispatcher = Dispatcher()
270
+ tester = BotTester.from_dispatcher(dispatcher)
271
+ ```
272
+ """
257
273
  bot_conversation = BotConversation(dispatcher=dispatcher, **kwargs)
258
- return cls(bot_conversation, command_prefix=command_prefix)
274
+ return cls(bot_conversation)
259
275
 
260
276
  @classmethod
261
- def from_routers(cls, *routers: aio.Router, **kwargs: Any) -> BotTester:
277
+ def from_routers(
278
+ cls,
279
+ *routers: aio.Router,
280
+ dependencies: Mapping[str, Any] | None = None,
281
+ middlewares: list[BaseMiddleware] | None = None,
282
+ **kwargs: Any,
283
+ ) -> BotTester:
284
+ """Create a tester from routers with optional dependencies and middleware.
285
+
286
+ Routers are deep-copied before they are attached to a new dispatcher, so
287
+ the same router fixtures can be reused by multiple tests. Dependencies are
288
+ added to aiogram's context data and injected into handlers by argument name.
289
+ Middleware instances are not copied and are registered, in the given order,
290
+ as inner middleware for both message and callback-query events.
291
+
292
+ Args:
293
+ *routers: Aiogram routers containing the handlers under test.
294
+ dependencies: Named objects added to aiogram's context data and made
295
+ available to handlers.
296
+ middlewares: Middleware instances to apply to messages and callback
297
+ queries. For other event types or outer middleware, configure a
298
+ dispatcher directly and use :meth:`from_dispatcher`.
299
+ **kwargs: Arguments forwarded to :class:`BotConversation`.
300
+
301
+ Example:
302
+
303
+ ```python
304
+ from aiogram import Router
305
+ from aiogram_bot_tester import BotTester
306
+
307
+ router = Router()
308
+ repository = object()
309
+ tester = BotTester.from_routers(
310
+ router,
311
+ dependencies={"repository": repository},
312
+ )
313
+ ```
314
+ """
262
315
  dispatcher = aio.Dispatcher(storage=fsm_memory.MemoryStorage())
316
+ dispatcher.workflow_data.update(dependencies or {})
317
+
318
+ for middleware in middlewares or []:
319
+ dispatcher.message.middleware(middleware)
320
+ dispatcher.callback_query.middleware(middleware)
263
321
 
264
322
  # We perform deepcopy because of the fact, that a single router cannot
265
323
  # be attached to multiple dispatchers. This issues arises when a tester is
@@ -300,12 +358,12 @@ class BotTester:
300
358
  return await self.bot_conversation.send_message(text, timeout)
301
359
 
302
360
  async def send_command(
303
- self, command: str, *args: object, prefix: str = "/"
361
+ self, command: str, *args: object, command_prefix: str = "/"
304
362
  ) -> abt_types.BotMessage:
305
363
  """
306
364
  Sends a command to the bot.
307
365
  Converts each of the given `args` to `str` first.
308
- Accepts a prefix for the command, which defaults to `"/"`.
366
+ Accepts a `command_prefix`, which defaults to `"/"`.
309
367
  Prefer to use this method instead of `send_message` if possible.
310
368
 
311
369
  Example:
@@ -314,7 +372,7 @@ class BotTester:
314
372
  message = await tester.send_command("sum", 1, 2)
315
373
  ```
316
374
  """
317
- command = f"{prefix}{command}"
375
+ command = f"{command_prefix}{command}"
318
376
  if args:
319
377
  command = f"{command} {' '.join(str(arg) for arg in args)}"
320
378
  return await self.send_message(command)
@@ -336,7 +394,10 @@ class BotTester:
336
394
  ) -> abt_types.BotMessage:
337
395
  """
338
396
  Taps a button attached to the last sent by the bot message.
339
- If the button does not exist, raises `ValueError`.
397
+ Raises `NoBotMessageError` if the bot has not sent a message,
398
+ `ButtonNotFoundError` if no button has the specified label,
399
+ `AmbiguousButtonError` if multiple buttons have that label, or
400
+ `UrlButtonInteractionError` if the matching button opens a URL.
340
401
 
341
402
  Example:
342
403
 
@@ -384,7 +445,9 @@ class BotTester:
384
445
  Example:
385
446
 
386
447
  ```python
387
- class Form:
448
+ from aiogram.fsm.state import State, StatesGroup
449
+
450
+ class Form(StatesGroup):
388
451
  name = State()
389
452
 
390
453
  is_in_state = await tester.in_state(Form.name)
@@ -406,7 +469,21 @@ class BotTester:
406
469
  return all(key in data and data[key] == value for key, value in kwargs.items())
407
470
 
408
471
  async def assert_state(self, state: fsm_state.State | None) -> None:
409
- """Asserts that the bot is in the specified FSM state."""
472
+ """
473
+ Asserts that the bot is in the specified FSM state.
474
+ Pass `None` to assert that no FSM state is active.
475
+
476
+ Example:
477
+
478
+ ```python
479
+ from aiogram.fsm.state import State, StatesGroup
480
+
481
+ class Form(StatesGroup):
482
+ name = State()
483
+
484
+ await tester.assert_state(Form.name)
485
+ ```
486
+ """
410
487
  if not await self.in_state(state):
411
488
  actual = await self.bot_conversation.get_state()
412
489
  expected = state.state if state is not None else None
@@ -415,7 +492,21 @@ class BotTester:
415
492
  )
416
493
 
417
494
  async def refute_state(self, state: fsm_state.State | None) -> None:
418
- """Asserts that the bot is not in the specified FSM state."""
495
+ """
496
+ Asserts that the bot is not in the specified FSM state.
497
+ Pass `None` to assert that an FSM state is active.
498
+
499
+ Example:
500
+
501
+ ```python
502
+ from aiogram.fsm.state import State, StatesGroup
503
+
504
+ class Form(StatesGroup):
505
+ name = State()
506
+
507
+ await tester.refute_state(Form.name)
508
+ ```
509
+ """
419
510
  if await self.in_state(state):
420
511
  expected = state.state if state is not None else None
421
512
  raise AssertionError(
@@ -423,7 +514,16 @@ class BotTester:
423
514
  )
424
515
 
425
516
  async def assert_data(self, **kwargs: Any) -> None:
426
- """Asserts that the FSM data contains all specified key-value pairs."""
517
+ """
518
+ Asserts that the FSM data contains all specified key-value pairs.
519
+ Additional values stored in the FSM context are ignored.
520
+
521
+ Example:
522
+
523
+ ```python
524
+ await tester.assert_data(name="Bob", age=30)
525
+ ```
526
+ """
427
527
  if not await self.data_has(**kwargs):
428
528
  actual = await self.bot_conversation.get_data()
429
529
  raise AssertionError(
@@ -431,7 +531,16 @@ class BotTester:
431
531
  )
432
532
 
433
533
  async def refute_data(self, **kwargs: Any) -> None:
434
- """Asserts that the FSM data does not contain all specified pairs."""
534
+ """
535
+ Asserts that the FSM data does not contain all specified pairs.
536
+ The assertion succeeds if at least one pair is absent or has another value.
537
+
538
+ Example:
539
+
540
+ ```python
541
+ await tester.refute_data(name="Alice", age=30)
542
+ ```
543
+ """
435
544
  if await self.data_has(**kwargs):
436
545
  actual = await self.bot_conversation.get_data()
437
546
  raise AssertionError(
@@ -33,9 +33,15 @@ class BotMessage:
33
33
  Example:
34
34
 
35
35
  ```python
36
- keyboard = [[CallbackButton("Yes"), CallbackButton("No")], [CallbackButton("Cancel")]]
36
+ keyboard = [
37
+ [
38
+ CallbackButton("Yes", data="yes"),
39
+ CallbackButton("No", data="no"),
40
+ ],
41
+ [CallbackButton("Cancel", data="cancel")],
42
+ ]
37
43
  message = BotMessage("Agree?", keyboard)
38
- print(message.buttons()) # A list of callback buttons
44
+ print(message.buttons) # A list of callback buttons
39
45
  ```
40
46
  """
41
47
  return list(itertools.chain.from_iterable(self.keyboard))
@@ -43,8 +49,8 @@ class BotMessage:
43
49
  def is_empty(self) -> bool:
44
50
  """
45
51
  Checks whether a message is empty.
46
- A message is empty when it contains no text (`message_text` is `None`) and
47
- no keyboard (`attached_keyboard` is an empty `list`).
52
+ A message is empty when it contains no text (`text` is `None`) and
53
+ no keyboard (`keyboard` is an empty `list`).
48
54
 
49
55
  Example:
50
56
 
@@ -102,7 +108,15 @@ class BotMessage:
102
108
  )
103
109
 
104
110
  def assert_contains(self, text: str, *texts: str) -> None:
105
- """Asserts that the message contains at least one of the specified texts."""
111
+ """
112
+ Asserts that the message contains at least one of the specified texts.
113
+
114
+ Example:
115
+
116
+ ```python
117
+ message.assert_contains("Hello", "Welcome")
118
+ ```
119
+ """
106
120
  expected = (text, *texts)
107
121
  if not self.contains(*expected):
108
122
  target = repr(text) if not texts else f"any of {expected!r}"
@@ -111,7 +125,15 @@ class BotMessage:
111
125
  )
112
126
 
113
127
  def refute_contains(self, text: str, *texts: str) -> None:
114
- """Asserts that the message contains none of the specified texts."""
128
+ """
129
+ Asserts that the message contains none of the specified texts.
130
+
131
+ Example:
132
+
133
+ ```python
134
+ message.refute_contains("Error", "Failed")
135
+ ```
136
+ """
115
137
  expected = (text, *texts)
116
138
  if self.contains(*expected):
117
139
  found = tuple(
@@ -128,7 +150,16 @@ class BotMessage:
128
150
  pattern: str | re.Pattern[str],
129
151
  *patterns: str | re.Pattern[str],
130
152
  ) -> None:
131
- """Asserts that the message matches at least one specified expression."""
153
+ """
154
+ Asserts that the message matches at least one specified expression.
155
+ Matching is backed by `re.search`.
156
+
157
+ Example:
158
+
159
+ ```python
160
+ message.assert_matches(r"Order #\\d+", r"Request #\\d+")
161
+ ```
162
+ """
132
163
  expected = (pattern, *patterns)
133
164
  if not self.matches(*expected):
134
165
  target = repr(pattern) if not patterns else f"any of {expected!r}"
@@ -141,7 +172,16 @@ class BotMessage:
141
172
  pattern: str | re.Pattern[str],
142
173
  *patterns: str | re.Pattern[str],
143
174
  ) -> None:
144
- """Asserts that the message matches none of the specified expressions."""
175
+ """
176
+ Asserts that the message matches none of the specified expressions.
177
+ Matching is backed by `re.search`.
178
+
179
+ Example:
180
+
181
+ ```python
182
+ message.refute_matches(r"error", r"failed")
183
+ ```
184
+ """
145
185
  expected = (pattern, *patterns)
146
186
  matched = tuple(
147
187
  item
@@ -169,7 +209,16 @@ class BotMessage:
169
209
  return any(label == button.label for button in self.buttons)
170
210
 
171
211
  def assert_button(self, label: str) -> None:
172
- """Asserts that the message has a button with the specified label."""
212
+ """
213
+ Asserts that the message has a button with the specified label.
214
+ Reply, callback, and URL buttons are all considered.
215
+
216
+ Example:
217
+
218
+ ```python
219
+ message.assert_button("Continue")
220
+ ```
221
+ """
173
222
  if not self.has_button(label):
174
223
  labels = [button.label for button in self.buttons]
175
224
  raise AssertionError(
@@ -178,13 +227,22 @@ class BotMessage:
178
227
  )
179
228
 
180
229
  def refute_button(self, label: str) -> None:
181
- """Asserts that the message has no button with the specified label."""
230
+ """
231
+ Asserts that the message has no button with the specified label.
232
+ Reply, callback, and URL buttons are all considered.
233
+
234
+ Example:
235
+
236
+ ```python
237
+ message.refute_button("Cancel")
238
+ ```
239
+ """
182
240
  if self.has_button(label):
183
241
  raise AssertionError(
184
242
  f"Expected message not to have button {label!r}, but it was present."
185
243
  )
186
244
 
187
- def has_url_button(self, label: str, url: str) -> bool:
245
+ def has_url_button(self, label: str, *, url: str) -> bool:
188
246
  """
189
247
  Checks whether an inline button is attached with specified `label` and `url`.
190
248
 
@@ -200,9 +258,20 @@ class BotMessage:
200
258
  if isinstance(button, UrlButton)
201
259
  )
202
260
 
203
- def assert_url_button(self, label: str, url: str) -> None:
204
- """Asserts that the specified URL button is attached."""
205
- if not self.has_url_button(label, url):
261
+ def assert_url_button(self, label: str, *, url: str) -> None:
262
+ """
263
+ Asserts that a URL button with the specified label and URL is attached.
264
+
265
+ Example:
266
+
267
+ ```python
268
+ message.assert_url_button(
269
+ "Open documentation",
270
+ url="https://example.com/docs",
271
+ )
272
+ ```
273
+ """
274
+ if not self.has_url_button(label, url=url):
206
275
  available = [
207
276
  (button.label, button.url)
208
277
  for button in self.buttons
@@ -213,15 +282,26 @@ class BotMessage:
213
282
  f"but available URL buttons were {available!r}."
214
283
  )
215
284
 
216
- def refute_url_button(self, label: str, url: str) -> None:
217
- """Asserts that the specified URL button is not attached."""
218
- if self.has_url_button(label, url):
285
+ def refute_url_button(self, label: str, *, url: str) -> None:
286
+ """
287
+ Asserts that a URL button with the specified label and URL is not attached.
288
+
289
+ Example:
290
+
291
+ ```python
292
+ message.refute_url_button(
293
+ "Delete account",
294
+ url="https://example.com/delete",
295
+ )
296
+ ```
297
+ """
298
+ if self.has_url_button(label, url=url):
219
299
  raise AssertionError(
220
300
  f"Expected message not to have URL button {label!r} with url={url!r}, "
221
301
  "but it was present."
222
302
  )
223
303
 
224
- def has_callback_button(self, label: str, callback_data: str) -> bool:
304
+ def has_callback_button(self, label: str, *, callback_data: str) -> bool:
225
305
  """
226
306
  Checks whether an inline button is attached with specified `label` and `callback_data`.
227
307
 
@@ -237,9 +317,18 @@ class BotMessage:
237
317
  if isinstance(button, CallbackButton)
238
318
  )
239
319
 
240
- def assert_callback_button(self, label: str, callback_data: str) -> None:
241
- """Asserts that the specified callback button is attached."""
242
- if not self.has_callback_button(label, callback_data):
320
+ def assert_callback_button(self, label: str, *, callback_data: str) -> None:
321
+ """
322
+ Asserts that a callback button with the specified data is attached.
323
+ Both the button label and callback data must match.
324
+
325
+ Example:
326
+
327
+ ```python
328
+ message.assert_callback_button("Confirm", callback_data="confirm")
329
+ ```
330
+ """
331
+ if not self.has_callback_button(label, callback_data=callback_data):
243
332
  available = [
244
333
  (button.label, button.data)
245
334
  for button in self.buttons
@@ -251,9 +340,18 @@ class BotMessage:
251
340
  f"but available callback buttons were {available!r}."
252
341
  )
253
342
 
254
- def refute_callback_button(self, label: str, callback_data: str) -> None:
255
- """Asserts that the specified callback button is not attached."""
256
- if self.has_callback_button(label, callback_data):
343
+ def refute_callback_button(self, label: str, *, callback_data: str) -> None:
344
+ """
345
+ Asserts that a callback button with the specified data is not attached.
346
+ Both the button label and callback data must match.
347
+
348
+ Example:
349
+
350
+ ```python
351
+ message.refute_callback_button("Cancel", callback_data="cancel")
352
+ ```
353
+ """
354
+ if self.has_callback_button(label, callback_data=callback_data):
257
355
  raise AssertionError(
258
356
  "Expected message not to have callback button "
259
357
  f"{label!r} with callback_data={callback_data!r}, but it was present."
@@ -281,13 +379,36 @@ class BotMessage:
281
379
  return keyboard == [[button.label for button in row] for row in self.keyboard]
282
380
 
283
381
  def assert_keyboard(self, keyboard: list[list[str]]) -> None:
284
- """Asserts that the complete keyboard layout matches the expected layout."""
382
+ """
383
+ Asserts that the complete keyboard layout matches the expected layout.
384
+ Button labels, rows, and ordering must match exactly.
385
+
386
+ Example:
387
+
388
+ ```python
389
+ message.assert_keyboard([
390
+ ["Yes", "No"],
391
+ ["Cancel"],
392
+ ])
393
+ ```
394
+ """
285
395
  actual = [[button.label for button in row] for row in self.keyboard]
286
396
  if not self.has_keyboard(keyboard):
287
397
  raise AssertionError(f"Expected keyboard {keyboard!r}, but got {actual!r}.")
288
398
 
289
399
  def refute_keyboard(self, keyboard: list[list[str]]) -> None:
290
- """Asserts that the complete keyboard layout differs from the given layout."""
400
+ """
401
+ Asserts that the complete keyboard layout differs from the given layout.
402
+
403
+ Example:
404
+
405
+ ```python
406
+ message.refute_keyboard([
407
+ ["Delete"],
408
+ ["Cancel"],
409
+ ])
410
+ ```
411
+ """
291
412
  if self.has_keyboard(keyboard):
292
413
  raise AssertionError(
293
414
  f"Expected keyboard not to equal {keyboard!r}, but it matched exactly."