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.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,

View file

@ -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,

View file

@ -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)

View file

@ -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.

View file

@ -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.

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
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)

View file

@ -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

View file

@ -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.