A Python robot that edits Wikipedia and interacts with people over IRC https://en.wikipedia.org/wiki/User:EarwigBot
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.

conftest.py 4.9 KiB

3 mesi fa
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152
  1. # Copyright (C) 2009-2024 Ben Kurtovic <ben.kurtovic@gmail.com>
  2. #
  3. # Permission is hereby granted, free of charge, to any person obtaining a copy
  4. # of this software and associated documentation files (the "Software"), to deal
  5. # in the Software without restriction, including without limitation the rights
  6. # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  7. # copies of the Software, and to permit persons to whom the Software is
  8. # furnished to do so, subject to the following conditions:
  9. #
  10. # The above copyright notice and this permission notice shall be included in
  11. # all copies or substantial portions of the Software.
  12. #
  13. # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  14. # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  15. # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  16. # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  17. # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  18. # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  19. # SOFTWARE.
  20. """
  21. EarwigBot's Unit Tests
  22. This conftest provides some support code for unit tests.
  23. Fixtures:
  24. -- ``command`` creates a mock connection and provides some helpful methods for
  25. testing IRC commands.
  26. Mock objects:
  27. -- ``MockBot`` implements ``Bot``, using the ``Mock`` equivalents of all objects
  28. whenever possible.
  29. -- ``MockBotConfig`` implements ``BotConfig`` with silent logging.
  30. -- ``MockIRCConnection`` implements ``IRCConnection``, using an internal string
  31. buffer for data instead of sending it over a socket.
  32. """
  33. import logging
  34. import os.path
  35. import re
  36. from collections.abc import Iterable, Sequence
  37. from threading import Lock
  38. import pytest
  39. from earwigbot.bot import Bot
  40. from earwigbot.commands import Command
  41. from earwigbot.config import BotConfig
  42. from earwigbot.irc import Data, IRCConnection
  43. from earwigbot.managers import CommandManager, TaskManager
  44. from earwigbot.wiki import SitesDB
  45. @pytest.fixture
  46. def command():
  47. return MockCommand()
  48. class MockCommand:
  49. re_sender = re.compile(r":(.*?)!(.*?)@(.*?)\Z")
  50. def setup(self, command: type[Command]) -> None:
  51. self.bot = MockBot(os.path.dirname(__file__))
  52. self.command = command(self.bot)
  53. def get_single(self) -> str:
  54. data = self.bot.frontend._get().split("\n")
  55. line = data.pop(0)
  56. for remaining in data[1:]:
  57. self.bot.frontend._send(remaining)
  58. return line
  59. def assert_sent(self, msg: str) -> None:
  60. line = self.get_single()
  61. assert line == msg
  62. def assert_sent_in(self, msgs: Iterable[str]) -> None:
  63. line = self.get_single()
  64. assert line in msgs
  65. def assert_said(self, msg: str) -> None:
  66. self.assert_sent(f"PRIVMSG #channel :{msg}")
  67. def assert_said_in(self, msgs: Iterable[str]) -> None:
  68. msgs = [f"PRIVMSG #channel :{msg}" for msg in msgs]
  69. self.assert_sent_in(msgs)
  70. def assert_reply(self, msg: str) -> None:
  71. self.assert_said(f"\x02Foo\x0f: {msg}")
  72. def assert_reply_in(self, msgs: Iterable[str]) -> None:
  73. msgs = [f"\x02Foo\x0f: {msg}" for msg in msgs]
  74. self.assert_said_in(msgs)
  75. def _make(self, line: Sequence[str]) -> Data:
  76. return Data(self.bot.frontend.nick, line, line[1])
  77. def make_msg(self, command, *args):
  78. line = f":Foo!bar@example.com PRIVMSG #channel :!{command}"
  79. line = line.strip().split()
  80. line.extend(args)
  81. return self._make(line)
  82. def make_join(self):
  83. line = ":Foo!bar@example.com JOIN :#channel".strip().split()
  84. return self._make(line)
  85. class MockBot(Bot):
  86. def __init__(self, root_dir: str, level=logging.INFO) -> None:
  87. self.config = MockBotConfig(self, root_dir, level)
  88. self.logger = logging.getLogger("earwigbot")
  89. self.commands = CommandManager(self)
  90. self.tasks = TaskManager(self)
  91. self.wiki = SitesDB(self)
  92. self.frontend = MockIRCConnection(self)
  93. self.watcher = MockIRCConnection(self)
  94. self.component_lock = Lock()
  95. self._keep_looping = True
  96. class MockBotConfig(BotConfig):
  97. def _setup_logging(self) -> None:
  98. logger = logging.getLogger("earwigbot")
  99. logger.addHandler(logging.NullHandler())
  100. class MockIRCConnection(IRCConnection):
  101. def __init__(self, bot: MockBot) -> None:
  102. super().__init__(
  103. "localhost",
  104. 6667,
  105. "MockBot",
  106. "mock",
  107. "Mock Bot",
  108. bot.logger.getChild("mock"),
  109. )
  110. self._buffer = ""
  111. def _connect(self) -> None:
  112. self._buffer = ""
  113. def _close(self) -> None:
  114. self._buffer = ""
  115. def _get(self, size: int = 4096) -> str:
  116. data, self._buffer = self._buffer, ""
  117. return data
  118. def _send(self, msg: str, hidelog: bool = False) -> None:
  119. self._buffer += msg + "\n"