flake8, pydocstyle, pyupgrade → ruff

This commit is contained in:
Guilhem Saurel
2023-03-09 00:07:23 +01:00
parent a3555a6ff8
commit f90a21e4e6
16 changed files with 69 additions and 59 deletions

View File

@@ -21,26 +21,17 @@ repos:
rev: 5.12.0 rev: 5.12.0
hooks: hooks:
- id: isort - id: isort
- repo: https://github.com/PyCQA/pydocstyle
rev: 6.3.0
hooks:
- id: pydocstyle
- repo: https://github.com/PyCQA/flake8
rev: 6.0.0
hooks:
- id: flake8
- repo: https://github.com/psf/black - repo: https://github.com/psf/black
rev: 23.1.0 rev: 23.1.0
hooks: hooks:
- id: black - id: black
- repo: https://github.com/asottile/pyupgrade
rev: v3.3.1
hooks:
- id: pyupgrade
args:
- --py38-plus
- repo: https://github.com/pappasam/toml-sort - repo: https://github.com/pappasam/toml-sort
rev: v0.22.4 rev: v0.22.4
hooks: hooks:
- id: toml-sort-fix - id: toml-sort-fix
exclude: 'poetry.lock' exclude: 'poetry.lock'
- repo: https://github.com/charliermarsh/ruff-pre-commit
rev: v0.0.254
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]

View File

@@ -6,6 +6,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
## [Unreleased] ## [Unreleased]
- tools: flake8, pydocstyle, pyupgrade → ruff
## [v3.7.0] - 2023-03-08 ## [v3.7.0] - 2023-03-08
- Add support for using predefined access tokens - Add support for using predefined access tokens

View File

@@ -12,8 +12,7 @@ LOGGER = logging.getLogger("matrix_webhook.app")
async def main(event): async def main(event):
""" """Launch main coroutine.
Launch main coroutine.
matrix client login & start web server matrix client login & start web server
""" """

View File

@@ -34,7 +34,7 @@ parser.add_argument(
), ),
) )
auth = parser.add_mutually_exclusive_group( auth = parser.add_mutually_exclusive_group(
required=all(v not in os.environ for v in ["MATRIX_PW", "MATRIX_TOKEN"]) required=all(v not in os.environ for v in ["MATRIX_PW", "MATRIX_TOKEN"]),
) )
auth.add_argument( auth.add_argument(
"-p", "-p",
@@ -61,7 +61,11 @@ parser.add_argument(
), ),
) )
parser.add_argument( parser.add_argument(
"-v", "--verbose", action="count", default=0, help="increment verbosity level" "-v",
"--verbose",
action="count",
default=0,
help="increment verbosity level",
) )
args = parser.parse_args() args = parser.parse_args()

View File

@@ -13,8 +13,7 @@ LOGGER = logging.getLogger("matrix_webhook.handler")
async def matrix_webhook(request): async def matrix_webhook(request):
""" """Coroutine given to the server, st. it knows what to do with an HTTP request.
Coroutine given to the server, st. it knows what to do with an HTTP request.
This one handles a POST, checks its content, and forwards it to the matrix room. This one handles a POST, checks its content, and forwards it to the matrix room.
""" """
@@ -37,11 +36,13 @@ async def matrix_webhook(request):
if "formatter" in request.rel_url.query: if "formatter" in request.rel_url.query:
try: try:
data = getattr(formatters, request.rel_url.query["formatter"])( data = getattr(formatters, request.rel_url.query["formatter"])(
data, request.headers data,
request.headers,
) )
except AttributeError: except AttributeError:
return utils.create_json_response( return utils.create_json_response(
HTTPStatus.BAD_REQUEST, "Unknown formatter" HTTPStatus.BAD_REQUEST,
"Unknown formatter",
) )
if "room_id" in request.rel_url.query and "room_id" not in data: if "room_id" in request.rel_url.query and "room_id" not in data:
@@ -56,7 +57,8 @@ async def matrix_webhook(request):
data["key"] = conf.API_KEY data["key"] = conf.API_KEY
else: # but if there is a wrong digest, an informative error should be provided else: # but if there is a wrong digest, an informative error should be provided
return utils.create_json_response( return utils.create_json_response(
HTTPStatus.UNAUTHORIZED, "Invalid SHA-256 HMAC digest" HTTPStatus.UNAUTHORIZED,
"Invalid SHA-256 HMAC digest",
) )
missing = [] missing = []
@@ -65,7 +67,8 @@ async def matrix_webhook(request):
missing.append(key) missing.append(key)
if missing: if missing:
return utils.create_json_response( return utils.create_json_response(
HTTPStatus.BAD_REQUEST, f"Missing {', '.join(missing)}" HTTPStatus.BAD_REQUEST,
f"Missing {', '.join(missing)}",
) )
if data["key"] != conf.API_KEY: if data["key"] != conf.API_KEY:

View File

@@ -63,7 +63,9 @@ async def send_room_message(room_id, content):
for _ in range(10): for _ in range(10):
try: try:
resp = await CLIENT.room_send( resp = await CLIENT.room_send(
room_id=room_id, message_type="m.room.message", content=content room_id=room_id,
message_type="m.room.message",
content=content,
) )
if isinstance(resp, RoomSendError): if isinstance(resp, RoomSendError):
if resp.status_code == "M_UNKNOWN_TOKEN": if resp.status_code == "M_UNKNOWN_TOKEN":

View File

@@ -38,5 +38,10 @@ matrix-webhook = "matrix_webhook.__main__:main"
[tool.poetry.urls] [tool.poetry.urls]
"changelog" = "https://github.com/nim65s/matrix-webhook/blob/master/CHANGELOG.md" "changelog" = "https://github.com/nim65s/matrix-webhook/blob/master/CHANGELOG.md"
[tool.ruff]
extend-ignore = ["D203", "D213"]
extend-select = ["A", "B", "C", "COM", "D", "EM", "EXE", "G", "N", "PTH", "RET", "RUF", "UP", "W", "YTT"]
target-version = "py38"
[tool.tomlsort] [tool.tomlsort]
all = true all = true

View File

@@ -1,2 +0,0 @@
[flake8]
max-line-length = 88

View File

@@ -4,6 +4,7 @@
import argparse import argparse
import logging import logging
from os import environ from os import environ
from pathlib import Path
from subprocess import Popen, run from subprocess import Popen, run
from time import time from time import time
from unittest import main from unittest import main
@@ -21,7 +22,11 @@ LOGGER = logging.getLogger("matrix-webhook.tests.start")
parser = argparse.ArgumentParser(description=__doc__) parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument( parser.add_argument(
"-v", "--verbose", action="count", default=0, help="increment verbosity level" "-v",
"--verbose",
action="count",
default=0,
help="increment verbosity level",
) )
@@ -77,14 +82,14 @@ def run_and_test():
"synapse.app.homeserver", "synapse.app.homeserver",
"--config-path", "--config-path",
"/srv/homeserver.yaml", "/srv/homeserver.yaml",
] ],
) )
if not wait_available(f"{MATRIX_URL}/_matrix/client/r0/login", "flows"): if not wait_available(f"{MATRIX_URL}/_matrix/client/r0/login", "flows"):
return False return False
# Register a user for the bot. # Register a user for the bot.
LOGGER.info("Registering the bot") LOGGER.info("Registering the bot")
with open("/srv/homeserver.yaml") as f: with Path("/srv/homeserver.yaml").open() as f:
secret = yaml.safe_load(f.read()).get("registration_shared_secret", None) secret = yaml.safe_load(f.read()).get("registration_shared_secret", None)
request_registration(MATRIX_ID, MATRIX_PW, MATRIX_URL, secret, admin=True) request_registration(MATRIX_ID, MATRIX_PW, MATRIX_URL, secret, admin=True)

View File

@@ -1,6 +1,7 @@
"""Test module for grafana formatter.""" """Test module for grafana formatter."""
import unittest import unittest
from pathlib import Path
import httpx import httpx
import nio import nio
@@ -39,7 +40,7 @@ class GithubFormatterTest(unittest.IsolatedAsyncioTestCase):
await client.login(MATRIX_PW) await client.login(MATRIX_PW)
room = await client.room_create() room = await client.room_create()
with open("tests/example_github_push.json", "rb") as f: with Path("tests/example_github_push.json", "rb").open() as f:
example_github_push = f.read().strip() example_github_push = f.read().strip()
self.assertEqual( self.assertEqual(
httpx.post( httpx.post(
@@ -72,7 +73,7 @@ class GithubFormatterTest(unittest.IsolatedAsyncioTestCase):
await client.login(MATRIX_PW) await client.login(MATRIX_PW)
room = await client.room_create() room = await client.room_create()
with open("tests/example_github_push.json", "rb") as f: with Path("tests/example_github_push.json").open("rb") as f:
example_github_push = f.read().strip() example_github_push = f.read().strip()
self.assertEqual( self.assertEqual(
httpx.post( httpx.post(
@@ -92,11 +93,11 @@ class GithubFormatterTest(unittest.IsolatedAsyncioTestCase):
before = "ac7d1d9647008145e9d0cf65d24744d0db4862b8" before = "ac7d1d9647008145e9d0cf65d24744d0db4862b8"
after = "4bcdb25c809391baaabc264d9309059f9f48ead2" after = "4bcdb25c809391baaabc264d9309059f9f48ead2"
GH = "https://github.com" gh = "https://github.com"
expected = f'<p><a href="{GH}/nim65s">@nim65s</a> pushed on refs/heads/devel: ' expected = f'<p><a href="{gh}/nim65s">@nim65s</a> pushed on refs/heads/devel: '
expected += f'<a href="{GH}/nim65s/matrix-webhook/compare/ac7d1d964700...' expected += f'<a href="{gh}/nim65s/matrix-webhook/compare/ac7d1d964700...'
expected += f'4bcdb25c8093">{before}{after}</a>:</p>\n<ul>\n<li>' expected += f'4bcdb25c8093">{before}{after}</a>:</p>\n<ul>\n<li>'
expected += f'<a href="{GH}/nim65s/matrix-webhook/commit/{after}">' expected += f'<a href="{gh}/nim65s/matrix-webhook/commit/{after}">'
expected += "formatters: also get headers</a></li>\n</ul>" expected += "formatters: also get headers</a></li>\n</ul>"
message = messages.chunk[0] message = messages.chunk[0]
@@ -113,7 +114,7 @@ class GithubFormatterTest(unittest.IsolatedAsyncioTestCase):
await client.login(MATRIX_PW) await client.login(MATRIX_PW)
room = await client.room_create() room = await client.room_create()
with open("tests/example_github_push.json", "rb") as f: with Path("tests/example_github_push.json").open("rb") as f:
example_github_push = f.read().strip() example_github_push = f.read().strip()
self.assertEqual( self.assertEqual(

View File

@@ -1,9 +1,7 @@
""" """Test module for gitlab "google chat" formatter."""
Test module for gitlab "google chat" formatter.
"""
import unittest import unittest
from pathlib import Path
import httpx import httpx
import nio import nio
@@ -22,7 +20,7 @@ class GitlabGchatFormatterTest(unittest.IsolatedAsyncioTestCase):
await client.login(MATRIX_PW) await client.login(MATRIX_PW)
room = await client.room_create() room = await client.room_create()
with open("tests/example_gitlab_gchat.json") as f: with Path("tests/example_gitlab_gchat.json").open() as f:
example_gitlab_gchat_request = f.read() example_gitlab_gchat_request = f.read()
self.assertEqual( self.assertEqual(
httpx.post( httpx.post(

View File

@@ -1,9 +1,7 @@
""" """Test module for gitlab "teams" formatter."""
Test module for gitlab "teams" formatter.
"""
import unittest import unittest
from pathlib import Path
import httpx import httpx
import nio import nio
@@ -22,7 +20,7 @@ class GitlabTeamsFormatterTest(unittest.IsolatedAsyncioTestCase):
await client.login(MATRIX_PW) await client.login(MATRIX_PW)
room = await client.room_create() room = await client.room_create()
with open("tests/example_gitlab_teams.json") as f: with Path("tests/example_gitlab_teams.json").open() as f:
example_gitlab_teams_request = f.read() example_gitlab_teams_request = f.read()
self.assertEqual( self.assertEqual(
httpx.post( httpx.post(

View File

@@ -1,10 +1,10 @@
""" """Test module for grafana formatter.
Test module for grafana formatter.
ref https://grafana.com/docs/grafana/latest/alerting/old-alerting/notifications/#webhook ref https://grafana.com/docs/grafana/latest/alerting/old-alerting/notifications/#webhook
""" """
import unittest import unittest
from pathlib import Path
import httpx import httpx
import nio import nio
@@ -23,7 +23,7 @@ class GrafanaFormatterTest(unittest.IsolatedAsyncioTestCase):
await client.login(MATRIX_PW) await client.login(MATRIX_PW)
room = await client.room_create() room = await client.room_create()
with open("tests/example_grafana.json") as f: with Path("tests/example_grafana.json").open() as f:
example_grafana_request = f.read() example_grafana_request = f.read()
self.assertEqual( self.assertEqual(
httpx.post( httpx.post(

View File

@@ -1,10 +1,10 @@
""" """Test module for grafana v9 formatter.
Test module for grafana v9 formatter.
ref https://grafana.com/docs/grafana/latest/alerting/old-alerting/notifications/#webhook ref https://grafana.com/docs/grafana/latest/alerting/old-alerting/notifications/#webhook
""" """
import unittest import unittest
from pathlib import Path
import httpx import httpx
import nio import nio
@@ -23,7 +23,7 @@ class Grafana9xFormatterTest(unittest.IsolatedAsyncioTestCase):
await client.login(MATRIX_PW) await client.login(MATRIX_PW)
room = await client.room_create() room = await client.room_create()
with open("tests/example_grafana_9x.json") as f: with Path("tests/example_grafana_9x.json").open() as f:
example_grafana_request = f.read() example_grafana_request = f.read()
self.assertEqual( self.assertEqual(
httpx.post( httpx.post(

View File

@@ -1,10 +1,10 @@
""" """Test version 9 compatibility of grafana formatter.
Test version 9 compatibility of grafana formatter.
ref https://grafana.com/docs/grafana/latest/alerting/old-alerting/notifications/#webhook ref https://grafana.com/docs/grafana/latest/alerting/old-alerting/notifications/#webhook
""" """
import unittest import unittest
from pathlib import Path
import httpx import httpx
import nio import nio
@@ -23,7 +23,7 @@ class GrafanaForwardFormatterTest(unittest.IsolatedAsyncioTestCase):
await client.login(MATRIX_PW) await client.login(MATRIX_PW)
room = await client.room_create() room = await client.room_create()
with open("tests/example_grafana_9x.json") as f: with Path("tests/example_grafana_9x.json").open() as f:
example_grafana_request = f.read() example_grafana_request = f.read()
self.assertEqual( self.assertEqual(
httpx.post( httpx.post(

View File

@@ -50,7 +50,8 @@ class BotTest(unittest.IsolatedAsyncioTestCase):
room = await client.room_create() room = await client.room_create()
self.assertEqual( self.assertEqual(
bot_req({"text": text}, KEY, room.room_id), {"status": 200, "ret": "OK"} bot_req({"text": text}, KEY, room.room_id),
{"status": 200, "ret": "OK"},
) )
sync = await client.sync() sync = await client.sync()
@@ -118,7 +119,8 @@ class BotTest(unittest.IsolatedAsyncioTestCase):
room = await client.room_create() room = await client.room_create()
self.assertEqual( self.assertEqual(
bot_req({"body": body}, KEY, room.room_id), {"status": 200, "ret": "OK"} bot_req({"body": body}, KEY, room.room_id),
{"status": 200, "ret": "OK"},
) )
sync = await client.sync() sync = await client.sync()
@@ -142,7 +144,9 @@ class BotTest(unittest.IsolatedAsyncioTestCase):
self.assertEqual( self.assertEqual(
bot_req( bot_req(
{"body": body, "formatted_body": formatted_body}, KEY, room.room_id {"body": body, "formatted_body": formatted_body},
KEY,
room.room_id,
), ),
{"status": 200, "ret": "OK"}, {"status": 200, "ret": "OK"},
) )