Refactor(backend): improve formatting in services, repositories & tests

- Consistently format multi-line function headers, exception handling, and repository method calls for readability.
- Reorganize misplaced imports across modules (e.g., services & tests) into proper sorted order.
- Adjust indentation, line breaks, and spacing inconsistencies in tests and migration files.
- Cleanup unnecessary trailing newlines and reorganize `__all__` declarations for consistency.
This commit is contained in:
2026-02-28 18:37:56 +01:00
parent 98b455fdc3
commit 4c6bf55bcc
38 changed files with 567 additions and 337 deletions

View File

@@ -12,8 +12,8 @@ These tests prevent real-world attack scenarios.
import pytest
from httpx import AsyncClient
from app.repositories.session import session_repo as session_crud
from app.models.user import User
from app.repositories.session import session_repo as session_crud
class TestRevokedSessionSecurity:

View File

@@ -11,9 +11,9 @@ These tests prevent unauthorized access and privilege escalation.
import pytest
from httpx import AsyncClient
from app.repositories.user import user_repo as user_crud
from app.models.organization import Organization
from app.models.user import User
from app.repositories.user import user_repo as user_crud
class TestInactiveUserBlocking:

View File

@@ -99,7 +99,8 @@ class TestUpdateCurrentUser:
from unittest.mock import patch
with patch(
"app.api.routes.users.user_service.update_user", side_effect=Exception("DB error")
"app.api.routes.users.user_service.update_user",
side_effect=Exception("DB error"),
):
with pytest.raises(Exception):
await client.patch(
@@ -224,7 +225,8 @@ class TestUpdateUserById:
from unittest.mock import patch
with patch(
"app.api.routes.users.user_service.update_user", side_effect=ValueError("Invalid")
"app.api.routes.users.user_service.update_user",
side_effect=ValueError("Invalid"),
):
with pytest.raises(ValueError):
await client.patch(
@@ -241,7 +243,8 @@ class TestUpdateUserById:
from unittest.mock import patch
with patch(
"app.api.routes.users.user_service.update_user", side_effect=Exception("Unexpected")
"app.api.routes.users.user_service.update_user",
side_effect=Exception("Unexpected"),
):
with pytest.raises(Exception):
await client.patch(

View File

@@ -170,7 +170,9 @@ class TestCRUDBaseCreate:
last_name="User",
)
with pytest.raises(DuplicateEntryError, match="Database integrity error"):
with pytest.raises(
DuplicateEntryError, match="Database integrity error"
):
await user_crud.create(session, obj_in=user_data)
@pytest.mark.asyncio
@@ -307,7 +309,9 @@ class TestCRUDBaseUpdate:
"statement", {}, Exception("constraint failed")
),
):
with pytest.raises(IntegrityConstraintError, match="Database integrity error"):
with pytest.raises(
IntegrityConstraintError, match="Database integrity error"
):
await user_crud.update(
session, db_obj=user, obj_in={"first_name": "Test"}
)
@@ -327,7 +331,9 @@ class TestCRUDBaseUpdate:
"statement", {}, Exception("connection error")
),
):
with pytest.raises(IntegrityConstraintError, match="Database operation failed"):
with pytest.raises(
IntegrityConstraintError, match="Database operation failed"
):
await user_crud.update(
session, db_obj=user, obj_in={"first_name": "Test"}
)
@@ -408,7 +414,8 @@ class TestCRUDBaseRemove:
),
):
with pytest.raises(
IntegrityConstraintError, match="Cannot delete.*referenced by other records"
IntegrityConstraintError,
match="Cannot delete.*referenced by other records",
):
await user_crud.remove(session, id=str(async_test_user.id))
@@ -904,8 +911,8 @@ class TestCRUDBaseModelsWithoutSoftDelete:
_test_engine, SessionLocal = async_test_db
# Create an organization (which doesn't have deleted_at)
from app.repositories.organization import organization_repo as org_crud
from app.models.organization import Organization
from app.repositories.organization import organization_repo as org_crud
async with SessionLocal() as session:
org = Organization(name="Test Org", slug="test-org")
@@ -915,7 +922,9 @@ class TestCRUDBaseModelsWithoutSoftDelete:
# Try to soft delete organization (should fail)
async with SessionLocal() as session:
with pytest.raises(InvalidInputError, match="does not have a deleted_at column"):
with pytest.raises(
InvalidInputError, match="does not have a deleted_at column"
):
await org_crud.soft_delete(session, id=str(org_id))
@pytest.mark.asyncio
@@ -924,8 +933,8 @@ class TestCRUDBaseModelsWithoutSoftDelete:
_test_engine, SessionLocal = async_test_db
# Create an organization (which doesn't have deleted_at)
from app.repositories.organization import organization_repo as org_crud
from app.models.organization import Organization
from app.repositories.organization import organization_repo as org_crud
async with SessionLocal() as session:
org = Organization(name="Restore Test", slug="restore-test")
@@ -935,7 +944,9 @@ class TestCRUDBaseModelsWithoutSoftDelete:
# Try to restore organization (should fail)
async with SessionLocal() as session:
with pytest.raises(InvalidInputError, match="does not have a deleted_at column"):
with pytest.raises(
InvalidInputError, match="does not have a deleted_at column"
):
await org_crud.restore(session, id=str(org_id))
@@ -955,8 +966,8 @@ class TestCRUDBaseEagerLoadingWithRealOptions:
_test_engine, SessionLocal = async_test_db
# Create a session for the user
from app.repositories.session import session_repo as session_crud
from app.models.user_session import UserSession
from app.repositories.session import session_repo as session_crud
async with SessionLocal() as session:
user_session = UserSession(
@@ -994,8 +1005,8 @@ class TestCRUDBaseEagerLoadingWithRealOptions:
_test_engine, SessionLocal = async_test_db
# Create multiple sessions for the user
from app.repositories.session import session_repo as session_crud
from app.models.user_session import UserSession
from app.repositories.session import session_repo as session_crud
async with SessionLocal() as session:
for i in range(3):

View File

@@ -120,7 +120,9 @@ class TestBaseCRUDUpdateFailures:
with patch.object(
session, "rollback", new_callable=AsyncMock
) as mock_rollback:
with pytest.raises(IntegrityConstraintError, match="Database operation failed"):
with pytest.raises(
IntegrityConstraintError, match="Database operation failed"
):
await user_crud.update(
session, db_obj=user, obj_in={"first_name": "Updated"}
)
@@ -142,7 +144,9 @@ class TestBaseCRUDUpdateFailures:
with patch.object(
session, "rollback", new_callable=AsyncMock
) as mock_rollback:
with pytest.raises(IntegrityConstraintError, match="Database operation failed"):
with pytest.raises(
IntegrityConstraintError, match="Database operation failed"
):
await user_crud.update(
session, db_obj=user, obj_in={"first_name": "Updated"}
)

View File

@@ -63,7 +63,8 @@ class TestOAuthAccountCRUD:
# SQLite returns different error message than PostgreSQL
with pytest.raises(
DuplicateEntryError, match="(already linked|UNIQUE constraint failed|Failed to create)"
DuplicateEntryError,
match="(already linked|UNIQUE constraint failed|Failed to create)",
):
await oauth_account.create_account(session, obj_in=account_data2)

View File

@@ -10,9 +10,9 @@ import pytest
from sqlalchemy import select
from app.core.repository_exceptions import DuplicateEntryError, IntegrityConstraintError
from app.repositories.organization import organization_repo as organization_crud
from app.models.organization import Organization
from app.models.user_organization import OrganizationRole, UserOrganization
from app.repositories.organization import organization_repo as organization_crud
from app.schemas.organizations import OrganizationCreate
@@ -973,7 +973,9 @@ class TestOrganizationExceptionHandlers:
with patch.object(session, "commit", side_effect=mock_commit):
with patch.object(session, "rollback", new_callable=AsyncMock):
org_in = OrganizationCreate(name="Test", slug="test")
with pytest.raises(IntegrityConstraintError, match="Database integrity error"):
with pytest.raises(
IntegrityConstraintError, match="Database integrity error"
):
await organization_crud.create(session, obj_in=org_in)
@pytest.mark.asyncio
@@ -1059,7 +1061,8 @@ class TestOrganizationExceptionHandlers:
with patch.object(session, "commit", side_effect=mock_commit):
with patch.object(session, "rollback", new_callable=AsyncMock):
with pytest.raises(
IntegrityConstraintError, match="Failed to add user to organization"
IntegrityConstraintError,
match="Failed to add user to organization",
):
await organization_crud.add_user(
session,

View File

@@ -9,8 +9,8 @@ from uuid import uuid4
import pytest
from app.core.repository_exceptions import InvalidInputError
from app.repositories.session import session_repo as session_crud
from app.models.user_session import UserSession
from app.repositories.session import session_repo as session_crud
from app.schemas.sessions import SessionCreate

View File

@@ -11,8 +11,8 @@ import pytest
from sqlalchemy.exc import OperationalError
from app.core.repository_exceptions import IntegrityConstraintError
from app.repositories.session import session_repo as session_crud
from app.models.user_session import UserSession
from app.repositories.session import session_repo as session_crud
from app.schemas.sessions import SessionCreate
@@ -103,7 +103,9 @@ class TestSessionCRUDCreateSessionFailures:
last_used_at=datetime.now(UTC),
)
with pytest.raises(IntegrityConstraintError, match="Failed to create session"):
with pytest.raises(
IntegrityConstraintError, match="Failed to create session"
):
await session_crud.create_session(session, obj_in=session_data)
mock_rollback.assert_called_once()
@@ -134,7 +136,9 @@ class TestSessionCRUDCreateSessionFailures:
last_used_at=datetime.now(UTC),
)
with pytest.raises(IntegrityConstraintError, match="Failed to create session"):
with pytest.raises(
IntegrityConstraintError, match="Failed to create session"
):
await session_crud.create_session(session, obj_in=session_data)
mock_rollback.assert_called_once()

View File

@@ -4,12 +4,11 @@
import uuid
import pytest
import pytest_asyncio
from app.core.exceptions import NotFoundError
from app.models.user_organization import OrganizationRole
from app.schemas.organizations import OrganizationCreate, OrganizationUpdate
from app.services.organization_service import OrganizationService, organization_service
from app.services.organization_service import organization_service
def _make_org_create(name=None, slug=None) -> OrganizationCreate:
@@ -50,9 +49,7 @@ class TestGetOrganization:
_test_engine, AsyncTestingSessionLocal = async_test_db
async with AsyncTestingSessionLocal() as session:
with pytest.raises(NotFoundError):
await organization_service.get_organization(
session, str(uuid.uuid4())
)
await organization_service.get_organization(session, str(uuid.uuid4()))
class TestCreateOrganization:

View File

@@ -5,10 +5,9 @@ import uuid
from datetime import UTC, datetime, timedelta
import pytest
import pytest_asyncio
from app.schemas.sessions import SessionCreate
from app.services.session_service import SessionService, session_service
from app.services.session_service import session_service
def _make_session_create(user_id, jti=None) -> SessionCreate:

View File

@@ -4,13 +4,12 @@
import uuid
import pytest
import pytest_asyncio
from sqlalchemy import select
from app.core.exceptions import NotFoundError
from app.models.user import User
from app.schemas.users import UserCreate, UserUpdate
from app.services.user_service import UserService, user_service
from app.services.user_service import user_service
class TestGetUser: