aiogram_bot_tester 2.1.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.1.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)
@@ -53,7 +55,7 @@ pip install git+https://github.com/samedit66/aiogram-bot-tester.git
53
55
  - **Conversation-first API** — send messages and commands, start the bot, and tap reply or callback buttons by their visible labels.
54
56
  - **Readable assertions** — check message text, regular expressions, buttons, callback data, URLs, and complete keyboard layouts.
55
57
  - **FSM support** — assert the current state and inspect FSM data across multi-step conversation flows.
56
- - **Flexible test setup** — build a tester from reusable routers or an existing dispatcher and inject fake dependencies through middleware.
58
+ - **Flexible test setup** — build a tester from reusable routers or an existing dispatcher, pass fake dependencies directly, and attach middleware when needed.
57
59
 
58
60
  ## Quick example
59
61
 
@@ -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)
@@ -38,7 +40,7 @@ pip install git+https://github.com/samedit66/aiogram-bot-tester.git
38
40
  - **Conversation-first API** — send messages and commands, start the bot, and tap reply or callback buttons by their visible labels.
39
41
  - **Readable assertions** — check message text, regular expressions, buttons, callback data, URLs, and complete keyboard layouts.
40
42
  - **FSM support** — assert the current state and inspect FSM data across multi-step conversation flows.
41
- - **Flexible test setup** — build a tester from reusable routers or an existing dispatcher and inject fake dependencies through middleware.
43
+ - **Flexible test setup** — build a tester from reusable routers or an existing dispatcher, pass fake dependencies directly, and attach middleware when needed.
42
44
 
43
45
  ## Quick example
44
46
 
@@ -1,6 +1,6 @@
1
1
  [project]
2
2
  name = "aiogram_bot_tester"
3
- version = "2.1.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
@@ -250,7 +251,6 @@ class BotTester:
250
251
  """A bot functionality tester."""
251
252
 
252
253
  bot_conversation: BotConversation
253
- command_prefix: str = "/"
254
254
 
255
255
  @classmethod
256
256
  def from_dispatcher(cls, dispatcher: aio.Dispatcher, **kwargs: Any) -> BotTester:
@@ -258,36 +258,62 @@ class BotTester:
258
258
 
259
259
  Args:
260
260
  dispatcher: Configured aiogram dispatcher used to process test updates.
261
- **kwargs: Arguments forwarded to :class:`BotConversation`, plus the
262
- optional ``command_prefix`` argument.
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
+ ```
263
272
  """
264
- command_prefix = kwargs.pop("command_prefix", "/")
265
273
  bot_conversation = BotConversation(dispatcher=dispatcher, **kwargs)
266
- return cls(bot_conversation, command_prefix=command_prefix)
274
+ return cls(bot_conversation)
267
275
 
268
276
  @classmethod
269
277
  def from_routers(
270
278
  cls,
271
279
  *routers: aio.Router,
280
+ dependencies: Mapping[str, Any] | None = None,
272
281
  middlewares: list[BaseMiddleware] | None = None,
273
282
  **kwargs: Any,
274
283
  ) -> BotTester:
275
- """Create a tester from routers and optional event middleware.
284
+ """Create a tester from routers with optional dependencies and middleware.
276
285
 
277
286
  Routers are deep-copied before they are attached to a new dispatcher, so
278
- the same router fixtures can be reused by multiple tests. Middleware
279
- instances are not copied and are registered, in the given order, as inner
280
- middleware for both message and callback-query events.
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.
281
291
 
282
292
  Args:
283
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.
284
296
  middlewares: Middleware instances to apply to messages and callback
285
297
  queries. For other event types or outer middleware, configure a
286
298
  dispatcher directly and use :meth:`from_dispatcher`.
287
- **kwargs: Arguments forwarded to :class:`BotConversation`, plus the
288
- optional ``command_prefix`` argument.
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
+ ```
289
314
  """
290
315
  dispatcher = aio.Dispatcher(storage=fsm_memory.MemoryStorage())
316
+ dispatcher.workflow_data.update(dependencies or {})
291
317
 
292
318
  for middleware in middlewares or []:
293
319
  dispatcher.message.middleware(middleware)
@@ -332,12 +358,12 @@ class BotTester:
332
358
  return await self.bot_conversation.send_message(text, timeout)
333
359
 
334
360
  async def send_command(
335
- self, command: str, *args: object, prefix: str = "/"
361
+ self, command: str, *args: object, command_prefix: str = "/"
336
362
  ) -> abt_types.BotMessage:
337
363
  """
338
364
  Sends a command to the bot.
339
365
  Converts each of the given `args` to `str` first.
340
- Accepts a prefix for the command, which defaults to `"/"`.
366
+ Accepts a `command_prefix`, which defaults to `"/"`.
341
367
  Prefer to use this method instead of `send_message` if possible.
342
368
 
343
369
  Example:
@@ -346,7 +372,7 @@ class BotTester:
346
372
  message = await tester.send_command("sum", 1, 2)
347
373
  ```
348
374
  """
349
- command = f"{prefix}{command}"
375
+ command = f"{command_prefix}{command}"
350
376
  if args:
351
377
  command = f"{command} {' '.join(str(arg) for arg in args)}"
352
378
  return await self.send_message(command)
@@ -368,7 +394,10 @@ class BotTester:
368
394
  ) -> abt_types.BotMessage:
369
395
  """
370
396
  Taps a button attached to the last sent by the bot message.
371
- 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.
372
401
 
373
402
  Example:
374
403
 
@@ -416,7 +445,9 @@ class BotTester:
416
445
  Example:
417
446
 
418
447
  ```python
419
- class Form:
448
+ from aiogram.fsm.state import State, StatesGroup
449
+
450
+ class Form(StatesGroup):
420
451
  name = State()
421
452
 
422
453
  is_in_state = await tester.in_state(Form.name)
@@ -438,7 +469,21 @@ class BotTester:
438
469
  return all(key in data and data[key] == value for key, value in kwargs.items())
439
470
 
440
471
  async def assert_state(self, state: fsm_state.State | None) -> None:
441
- """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
+ """
442
487
  if not await self.in_state(state):
443
488
  actual = await self.bot_conversation.get_state()
444
489
  expected = state.state if state is not None else None
@@ -447,7 +492,21 @@ class BotTester:
447
492
  )
448
493
 
449
494
  async def refute_state(self, state: fsm_state.State | None) -> None:
450
- """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
+ """
451
510
  if await self.in_state(state):
452
511
  expected = state.state if state is not None else None
453
512
  raise AssertionError(
@@ -455,7 +514,16 @@ class BotTester:
455
514
  )
456
515
 
457
516
  async def assert_data(self, **kwargs: Any) -> None:
458
- """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
+ """
459
527
  if not await self.data_has(**kwargs):
460
528
  actual = await self.bot_conversation.get_data()
461
529
  raise AssertionError(
@@ -463,7 +531,16 @@ class BotTester:
463
531
  )
464
532
 
465
533
  async def refute_data(self, **kwargs: Any) -> None:
466
- """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
+ """
467
544
  if await self.data_has(**kwargs):
468
545
  actual = await self.bot_conversation.get_data()
469
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,7 +227,16 @@ 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."
@@ -201,7 +259,18 @@ class BotMessage:
201
259
  )
202
260
 
203
261
  def assert_url_button(self, label: str, *, url: str) -> None:
204
- """Asserts that the specified URL button is attached."""
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
+ """
205
274
  if not self.has_url_button(label, url=url):
206
275
  available = [
207
276
  (button.label, button.url)
@@ -214,7 +283,18 @@ class BotMessage:
214
283
  )
215
284
 
216
285
  def refute_url_button(self, label: str, *, url: str) -> None:
217
- """Asserts that the specified URL button is not attached."""
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
+ """
218
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}, "
@@ -238,7 +318,16 @@ class BotMessage:
238
318
  )
239
319
 
240
320
  def assert_callback_button(self, label: str, *, callback_data: str) -> None:
241
- """Asserts that the specified callback button is attached."""
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
+ """
242
331
  if not self.has_callback_button(label, callback_data=callback_data):
243
332
  available = [
244
333
  (button.label, button.data)
@@ -252,7 +341,16 @@ class BotMessage:
252
341
  )
253
342
 
254
343
  def refute_callback_button(self, label: str, *, callback_data: str) -> None:
255
- """Asserts that the specified callback button is not attached."""
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
+ """
256
354
  if self.has_callback_button(label, callback_data=callback_data):
257
355
  raise AssertionError(
258
356
  "Expected message not to have callback button "
@@ -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."