fix typing and configure mypy

This commit is contained in:
HgO 2022-06-14 23:37:54 +02:00
parent ad324c63c3
commit 6ab094acdc
9 changed files with 30 additions and 23 deletions

View file

@ -38,7 +38,7 @@ class Command:
self.event = event self.event = event
self.args = self.command.split()[1:] self.args = self.command.split()[1:]
async def process(self): async def process(self) -> None:
"""Process the command""" """Process the command"""
if self.command.startswith("echo"): if self.command.startswith("echo"):
await self._echo() await self._echo()
@ -49,12 +49,12 @@ class Command:
else: else:
await self._unknown_command() await self._unknown_command()
async def _echo(self): async def _echo(self) -> None:
"""Echo back the command's arguments""" """Echo back the command's arguments"""
response = " ".join(self.args) response = " ".join(self.args)
await send_text_to_room(self.client, self.room.room_id, response) 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""" """Make the bot react to the command message"""
# React with a start emoji # React with a start emoji
reaction = "" reaction = ""
@ -68,7 +68,7 @@ class Command:
self.client, self.room.room_id, self.event.event_id, reaction 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""" """Show the help text"""
if not self.args: if not self.args:
text = ( text = (
@ -87,7 +87,7 @@ class Command:
text = "Unknown help topic!" text = "Unknown help topic!"
await send_text_to_room(self.client, self.room.room_id, text) 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( await send_text_to_room(
self.client, self.client,
self.room.room_id, self.room.room_id,

View file

@ -1,5 +1,5 @@
import logging import logging
from typing import Optional, Union from typing import Optional, Union, Dict
from markdown import markdown from markdown import markdown
from nio import ( from nio import (
@ -22,7 +22,7 @@ async def send_text_to_room(
notice: bool = True, notice: bool = True,
markdown_convert: bool = True, markdown_convert: bool = True,
reply_to_event_id: Optional[str] = None, reply_to_event_id: Optional[str] = None,
) -> Union[RoomSendResponse, ErrorResponse]: ) -> None:
"""Send text to a matrix room. """Send text to a matrix room.
Args: 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}} content["m.relates_to"] = {"m.in_reply_to": {"event_id": reply_to_event_id}}
try: try:
return await client.room_send( await client.room_send(
room_id, room_id,
"m.room.message", "m.room.message",
content, 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""" """Callback for when an event fails to decrypt. Inform the user"""
logger.error( logger.error(
f"Failed to decrypt event '{event.event_id}' in room '{room.room_id}'!" 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( await send_text_to_room(
self.client, client,
room.room_id, room.room_id,
user_msg, user_msg,
reply_to_event_id=event.event_id, reply_to_event_id=event.event_id,

View file

@ -29,7 +29,7 @@ class Config:
# Parse and validate config options # Parse and validate config options
self._parse_config_values() self._parse_config_values()
def _parse_config_values(self): def _parse_config_values(self) -> None:
"""Read and validate each config option""" """Read and validate each config option"""
# Logging setup # Logging setup
formatter = logging.Formatter( formatter = logging.Formatter(
@ -46,17 +46,17 @@ class Config:
["logging", "file_logging", "filepath"], default="bot.log" ["logging", "file_logging", "filepath"], default="bot.log"
) )
if file_logging_enabled: if file_logging_enabled:
handler = logging.FileHandler(file_logging_filepath) file_handler = logging.FileHandler(file_logging_filepath)
handler.setFormatter(formatter) file_handler.setFormatter(formatter)
logger.addHandler(handler) logger.addHandler(file_handler)
console_logging_enabled = self._get_cfg( console_logging_enabled = self._get_cfg(
["logging", "console_logging", "enabled"], default=True ["logging", "console_logging", "enabled"], default=True
) )
if console_logging_enabled: if console_logging_enabled:
handler = logging.StreamHandler(sys.stdout) console_handler = logging.StreamHandler(sys.stdout)
handler.setFormatter(formatter) console_handler.setFormatter(formatter)
logger.addHandler(handler) logger.addHandler(console_handler)
# Storage setup # Storage setup
self.store_path = self._get_cfg(["storage", "store_path"], required=True) self.store_path = self._get_cfg(["storage", "store_path"], required=True)

View file

@ -23,7 +23,7 @@ from matrix_alertbot.storage import Storage
logger = logging.getLogger(__name__) logger = logging.getLogger(__name__)
async def main(): async def main() -> bool:
"""The first function that is run when starting the bot""" """The first function that is run when starting the bot"""
# Read user-configured options from a config file. # Read user-configured options from a config file.

View file

@ -112,7 +112,7 @@ class Storage:
# #
# logger.info("Database migrated to v1") # 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. """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. This allows for the support of queries that are compatible with both postgres and sqlite.

4
mypy.ini Normal file
View file

@ -0,0 +1,4 @@
[mypy]
ignore_missing_imports = True
disallow_untyped_defs = True
disallow_untyped_calls = True

View file

@ -1,10 +1,11 @@
#!/usr/bin/env python3 #!/usr/bin/env python3
import os import os
from typing import Dict, Tuple, Any
from setuptools import find_packages, setup 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""" """Execute a single python file to get the variables defined in it"""
result = {} result = {}
code = read_file(path_segments) code = read_file(path_segments)
@ -12,7 +13,7 @@ def exec_file(path_segments):
return result 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 """Read a file from the package. Takes a list of strings to join to
make the path""" make the path"""
file_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), *path_segments) file_path = os.path.join(os.path.abspath(os.path.dirname(__file__)), *path_segments)

View file

@ -24,7 +24,7 @@ class CallbacksTestCase(unittest.TestCase):
self.fake_client, self.fake_storage, self.fake_config self.fake_client, self.fake_storage, self.fake_config
) )
def test_invite(self): def test_invite(self) -> None:
"""Tests the callback for InviteMemberEvents""" """Tests the callback for InviteMemberEvents"""
# Tests that the bot attempts to join a room after being invited to it # Tests that the bot attempts to join a room after being invited to it

View file

@ -6,7 +6,7 @@ from matrix_alertbot.errors import ConfigError
class ConfigTestCase(unittest.TestCase): class ConfigTestCase(unittest.TestCase):
def test_get_cfg(self): def test_get_cfg(self) -> None:
"""Test that Config._get_cfg works correctly""" """Test that Config._get_cfg works correctly"""
# Here's our test dictionary. Pretend that this was parsed from a YAML config file. # Here's our test dictionary. Pretend that this was parsed from a YAML config file.