From 6ab094acdc05a8042b60736a02f426c7f5b1285e Mon Sep 17 00:00:00 2001 From: HgO Date: Tue, 14 Jun 2022 23:37:54 +0200 Subject: [PATCH] fix typing and configure mypy --- matrix_alertbot/bot_commands.py | 10 +++++----- matrix_alertbot/chat_functions.py | 12 +++++++----- matrix_alertbot/config.py | 14 +++++++------- matrix_alertbot/main.py | 2 +- matrix_alertbot/storage.py | 2 +- mypy.ini | 4 ++++ setup.py | 5 +++-- tests/test_callbacks.py | 2 +- tests/test_config.py | 2 +- 9 files changed, 30 insertions(+), 23 deletions(-) create mode 100644 mypy.ini diff --git a/matrix_alertbot/bot_commands.py b/matrix_alertbot/bot_commands.py index 6d96231..099bc79 100644 --- a/matrix_alertbot/bot_commands.py +++ b/matrix_alertbot/bot_commands.py @@ -38,7 +38,7 @@ class Command: self.event = event self.args = self.command.split()[1:] - async def process(self): + async def process(self) -> None: """Process the command""" if self.command.startswith("echo"): await self._echo() @@ -49,12 +49,12 @@ class Command: else: await self._unknown_command() - async def _echo(self): + async def _echo(self) -> None: """Echo back the command's arguments""" response = " ".join(self.args) await send_text_to_room(self.client, self.room.room_id, response) - async def _react(self): + async def _react(self) -> None: """Make the bot react to the command message""" # React with a start emoji reaction = "⭐" @@ -68,7 +68,7 @@ class Command: self.client, self.room.room_id, self.event.event_id, reaction ) - async def _show_help(self): + async def _show_help(self) -> None: """Show the help text""" if not self.args: text = ( @@ -87,7 +87,7 @@ class Command: text = "Unknown help topic!" await send_text_to_room(self.client, self.room.room_id, text) - async def _unknown_command(self): + async def _unknown_command(self) -> None: await send_text_to_room( self.client, self.room.room_id, diff --git a/matrix_alertbot/chat_functions.py b/matrix_alertbot/chat_functions.py index 136726f..ac77848 100644 --- a/matrix_alertbot/chat_functions.py +++ b/matrix_alertbot/chat_functions.py @@ -1,5 +1,5 @@ import logging -from typing import Optional, Union +from typing import Optional, Union, Dict from markdown import markdown from nio import ( @@ -22,7 +22,7 @@ async def send_text_to_room( notice: bool = True, markdown_convert: bool = True, reply_to_event_id: Optional[str] = None, -) -> Union[RoomSendResponse, ErrorResponse]: +) -> None: """Send text to a matrix room. Args: @@ -60,7 +60,7 @@ async def send_text_to_room( content["m.relates_to"] = {"m.in_reply_to": {"event_id": reply_to_event_id}} try: - return await client.room_send( + await client.room_send( room_id, "m.room.message", content, @@ -129,7 +129,9 @@ async def react_to_event( ) -async def decryption_failure(self, room: MatrixRoom, event: MegolmEvent) -> None: +async def decryption_failure( + client: AsyncClient, room: MatrixRoom, event: MegolmEvent +) -> None: """Callback for when an event fails to decrypt. Inform the user""" logger.error( f"Failed to decrypt event '{event.event_id}' in room '{room.room_id}'!" @@ -147,7 +149,7 @@ async def decryption_failure(self, room: MatrixRoom, event: MegolmEvent) -> None ) await send_text_to_room( - self.client, + client, room.room_id, user_msg, reply_to_event_id=event.event_id, diff --git a/matrix_alertbot/config.py b/matrix_alertbot/config.py index 7b4a908..916db90 100644 --- a/matrix_alertbot/config.py +++ b/matrix_alertbot/config.py @@ -29,7 +29,7 @@ class Config: # Parse and validate config options self._parse_config_values() - def _parse_config_values(self): + def _parse_config_values(self) -> None: """Read and validate each config option""" # Logging setup formatter = logging.Formatter( @@ -46,17 +46,17 @@ class Config: ["logging", "file_logging", "filepath"], default="bot.log" ) if file_logging_enabled: - handler = logging.FileHandler(file_logging_filepath) - handler.setFormatter(formatter) - logger.addHandler(handler) + file_handler = logging.FileHandler(file_logging_filepath) + file_handler.setFormatter(formatter) + logger.addHandler(file_handler) console_logging_enabled = self._get_cfg( ["logging", "console_logging", "enabled"], default=True ) if console_logging_enabled: - handler = logging.StreamHandler(sys.stdout) - handler.setFormatter(formatter) - logger.addHandler(handler) + console_handler = logging.StreamHandler(sys.stdout) + console_handler.setFormatter(formatter) + logger.addHandler(console_handler) # Storage setup self.store_path = self._get_cfg(["storage", "store_path"], required=True) diff --git a/matrix_alertbot/main.py b/matrix_alertbot/main.py index ddb8e11..b66e7c1 100644 --- a/matrix_alertbot/main.py +++ b/matrix_alertbot/main.py @@ -23,7 +23,7 @@ from matrix_alertbot.storage import Storage logger = logging.getLogger(__name__) -async def main(): +async def main() -> bool: """The first function that is run when starting the bot""" # Read user-configured options from a config file. diff --git a/matrix_alertbot/storage.py b/matrix_alertbot/storage.py index 580ebd1..8759f8a 100644 --- a/matrix_alertbot/storage.py +++ b/matrix_alertbot/storage.py @@ -112,7 +112,7 @@ class Storage: # # logger.info("Database migrated to v1") - def _execute(self, *args) -> None: + def _execute(self, *args: Any) -> None: """A wrapper around cursor.execute that transforms placeholder ?'s to %s for postgres. This allows for the support of queries that are compatible with both postgres and sqlite. diff --git a/mypy.ini b/mypy.ini new file mode 100644 index 0000000..874a468 --- /dev/null +++ b/mypy.ini @@ -0,0 +1,4 @@ +[mypy] +ignore_missing_imports = True +disallow_untyped_defs = True +disallow_untyped_calls = True diff --git a/setup.py b/setup.py index 1ad9775..21246d3 100644 --- a/setup.py +++ b/setup.py @@ -1,10 +1,11 @@ #!/usr/bin/env python3 import os +from typing import Dict, Tuple, Any from setuptools import find_packages, setup -def exec_file(path_segments): +def exec_file(path_segments: Tuple) -> Dict[str, Any]: """Execute a single python file to get the variables defined in it""" result = {} code = read_file(path_segments) @@ -12,7 +13,7 @@ def exec_file(path_segments): return result -def read_file(path_segments): +def read_file(path_segments: Tuple) -> str: """Read a file from the package. Takes a list of strings to join to make the path""" file_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), *path_segments) diff --git a/tests/test_callbacks.py b/tests/test_callbacks.py index 4abd4a3..79bccd2 100644 --- a/tests/test_callbacks.py +++ b/tests/test_callbacks.py @@ -24,7 +24,7 @@ class CallbacksTestCase(unittest.TestCase): self.fake_client, self.fake_storage, self.fake_config ) - def test_invite(self): + def test_invite(self) -> None: """Tests the callback for InviteMemberEvents""" # Tests that the bot attempts to join a room after being invited to it diff --git a/tests/test_config.py b/tests/test_config.py index a22b137..1184f02 100644 --- a/tests/test_config.py +++ b/tests/test_config.py @@ -6,7 +6,7 @@ from matrix_alertbot.errors import ConfigError class ConfigTestCase(unittest.TestCase): - def test_get_cfg(self): + def test_get_cfg(self) -> None: """Test that Config._get_cfg works correctly""" # Here's our test dictionary. Pretend that this was parsed from a YAML config file.