Skip to content

Commit

Permalink
✅ Add flake8-errmsg validation
Browse files Browse the repository at this point in the history
  • Loading branch information
jemrobinson committed Sep 24, 2024
1 parent 380e9ce commit 8876c26
Show file tree
Hide file tree
Showing 5 changed files with 46 additions and 16 deletions.
13 changes: 9 additions & 4 deletions guacamole_user_sync/postgresql/postgresql_backend.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

from sqlalchemy import create_engine
from sqlalchemy.engine import URL, Engine # type:ignore
from sqlalchemy.exc import SQLAlchemyError
from sqlalchemy.orm import Session
from sqlalchemy.sql.expression import TextClause

Expand Down Expand Up @@ -65,10 +66,14 @@ def delete(self, table: type[T], *filter_args: Any) -> None: # noqa: ANN401
session.query(table).delete()

def execute_commands(self, commands: list[TextClause]) -> None:
with self.session() as session: # type:ignore
with session.begin():
for command in commands:
session.execute(command)
try:
with self.session() as session: # type:ignore
with session.begin():
for command in commands:
session.execute(command)
except SQLAlchemyError:
logger.warning("Unable to execute PostgreSQL commands.")
raise

def query(self, table: type[T], **filter_kwargs: Any) -> list[T]: # noqa: ANN401
with self.session() as session: # type:ignore
Expand Down
8 changes: 4 additions & 4 deletions guacamole_user_sync/postgresql/postgresql_client.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
import secrets
from datetime import UTC, datetime

from sqlalchemy.exc import OperationalError
from sqlalchemy.exc import SQLAlchemyError

from guacamole_user_sync.models import (
LDAPGroup,
Expand Down Expand Up @@ -117,9 +117,9 @@ def assign_users_to_groups(
def ensure_schema(self, schema_version: SchemaVersion) -> None:
try:
self.backend.execute_commands(GuacamoleSchema.commands(schema_version))
except OperationalError as exc:
logger.warning("Unable to connect to the PostgreSQL server.")
raise PostgreSQLError("Unable to ensure PostgreSQL schema.") from exc
except SQLAlchemyError as exc:
msg = "Unable to ensure PostgreSQL schema."
raise PostgreSQLError(msg) from exc

def update(self, *, groups: list[LDAPGroup], users: list[LDAPUser]) -> None:
"""Update the relevant tables to match lists of LDAP users and groups."""
Expand Down
1 change: 1 addition & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,7 @@ select = [
"D", # pydocstyle
"DTZ", # flake8-datetimez
"E", # pycodestyle errors
"EM", # flake8-errmsg
"F", # pyflakes
"FBT", # flake8-boolean-trap
"I", # isort
Expand Down
24 changes: 16 additions & 8 deletions synchronise.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,23 +90,31 @@ def synchronise(

if __name__ == "__main__":
if not (ldap_host := os.getenv("LDAP_HOST", None)):
raise ValueError("LDAP_HOST is not defined")
msg = "LDAP_HOST is not defined"
raise ValueError(msg)
if not (ldap_group_base_dn := os.getenv("LDAP_GROUP_BASE_DN", None)):
raise ValueError("LDAP_GROUP_BASE_DN is not defined")
msg = "LDAP_GROUP_BASE_DN is not defined"
raise ValueError(msg)
if not (ldap_group_filter := os.getenv("LDAP_GROUP_FILTER", None)):
raise ValueError("LDAP_GROUP_FILTER is not defined")
msg = "LDAP_GROUP_FILTER is not defined"
raise ValueError(msg)

if not (ldap_user_base_dn := os.getenv("LDAP_USER_BASE_DN", None)):
raise ValueError("LDAP_USER_BASE_DN is not defined")
msg = "LDAP_USER_BASE_DN is not defined"
raise ValueError(msg)
if not (ldap_user_filter := os.getenv("LDAP_USER_FILTER", None)):
raise ValueError("LDAP_USER_FILTER is not defined")
msg = "LDAP_USER_FILTER is not defined"
raise ValueError(msg)

if not (postgresql_host_name := os.getenv("POSTGRESQL_HOST", None)):
raise ValueError("POSTGRESQL_HOST is not defined")
msg = "POSTGRESQL_HOST is not defined"
raise ValueError(msg)
if not (postgresql_password := os.getenv("POSTGRESQL_PASSWORD", None)):
raise ValueError("POSTGRESQL_PASSWORD is not defined")
msg = "POSTGRESQL_PASSWORD is not defined"
raise ValueError(msg)
if not (postgresql_user_name := os.getenv("POSTGRESQL_USERNAME", None)):
raise ValueError("POSTGRESQL_USERNAME is not defined")
msg = "POSTGRESQL_USERNAME is not defined"
raise ValueError(msg)

logging.basicConfig(
level=(
Expand Down
16 changes: 16 additions & 0 deletions tests/test_postgresql.py
Original file line number Diff line number Diff line change
Expand Up @@ -130,6 +130,22 @@ def test_execute_commands(self) -> None:
backend.execute_commands([command])
session.execute.assert_called_once_with(command)

def test_execute_commands_exception(
self,
caplog: pytest.LogCaptureFixture,
) -> None:
command = text("SELECT * FROM guacamole_entity;")
session = self.mock_session()
session.execute.side_effect = OperationalError(
statement="exception reason",
params=None,
orig=None,
)
backend = self.mock_backend(session=session)
with pytest.raises(OperationalError, match="SQL: exception reason"):
backend.execute_commands([command])
assert "Unable to execute PostgreSQL commands." in caplog.text

def test_query(self) -> None:
session = self.mock_session()
backend = self.mock_backend(session=session)
Expand Down

0 comments on commit 8876c26

Please sign in to comment.