test_points_commands.py 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  1. from __future__ import annotations
  2. import sys
  3. import types
  4. from types import SimpleNamespace
  5. from unittest.mock import AsyncMock
  6. import pytest
  7. @pytest.fixture
  8. def points_module(app_modules, monkeypatch):
  9. permissions = types.ModuleType("wbb.core.decorators.permissions")
  10. def admins_only(*_args, **_kwargs):
  11. return lambda function: function
  12. permissions.adminsOnly = admins_only
  13. monkeypatch.setitem(
  14. sys.modules, "wbb.core.decorators.permissions", permissions
  15. )
  16. module = app_modules.load("wbb.modules.points")
  17. return module
  18. def _checkin_message() -> SimpleNamespace:
  19. response = SimpleNamespace(
  20. chat=SimpleNamespace(id=-100, type=SimpleNamespace(value="supergroup")),
  21. id=11,
  22. )
  23. return SimpleNamespace(
  24. chat=SimpleNamespace(id=-100, type=SimpleNamespace(value="supergroup")),
  25. id=10,
  26. from_user=SimpleNamespace(
  27. id=20,
  28. username="customer",
  29. first_name="顾客",
  30. last_name=None,
  31. ),
  32. reply_text=AsyncMock(return_value=response),
  33. )
  34. @pytest.mark.parametrize(
  35. ("created", "expected_text"),
  36. [
  37. (True, "签到成功"),
  38. (False, "已经签到过"),
  39. ],
  40. )
  41. async def test_checkin_schedules_user_and_bot_messages_for_cleanup(
  42. points_module, monkeypatch, created, expected_text
  43. ):
  44. message = _checkin_message()
  45. account = {"balance": 10}
  46. cleanup = []
  47. monkeypatch.setattr(
  48. points_module,
  49. "award_checkin",
  50. AsyncMock(return_value=(account, created)),
  51. )
  52. monkeypatch.setattr(
  53. points_module,
  54. "get_point_rules",
  55. AsyncMock(return_value={"checkin_points": 10}),
  56. )
  57. monkeypatch.setattr(
  58. points_module,
  59. "schedule_group_cleanup",
  60. lambda *messages: cleanup.extend(messages),
  61. )
  62. response = await points_module.points_checkin_command(None, message)
  63. assert expected_text in message.reply_text.await_args.args[0]
  64. assert cleanup == [message, response]
  65. async def test_checkin_error_schedules_user_and_bot_messages_for_cleanup(
  66. points_module, monkeypatch
  67. ):
  68. message = _checkin_message()
  69. cleanup = []
  70. monkeypatch.setattr(
  71. points_module,
  72. "award_checkin",
  73. AsyncMock(side_effect=points_module.PointsError("签到暂不可用")),
  74. )
  75. monkeypatch.setattr(
  76. points_module,
  77. "schedule_group_cleanup",
  78. lambda *messages: cleanup.extend(messages),
  79. )
  80. response = await points_module.points_checkin_command(None, message)
  81. assert message.reply_text.await_args.args == ("签到暂不可用",)
  82. assert cleanup == [message, response]