From 9cf0e40f80a6594999b767f2fe004d35eab49ab4 Mon Sep 17 00:00:00 2001 From: DarynaBb Date: Wed, 25 Nov 2026 14:41:38 +0100 Subject: [PATCH 1/2] ci(api): check ruff format in backend job --- .github/workflows/ci.yml | 1 + README.md | 9 +++++++++ 2 files changed, 10 insertions(+) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 11f255d..8a602e7 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -23,6 +23,7 @@ jobs: cache-dependency-path: backend/requirements*.txt - run: python -m pip install -r requirements-dev.txt - run: python -m ruff check . + - run: python -m ruff format --check . - run: python -m pytest mobile: runs-on: ubuntu-latest diff --git a/README.md b/README.md index 32438ce..25611a2 100644 --- a/README.md +++ b/README.md @@ -59,6 +59,15 @@ docker compose run --rm backend alembic upgrade head Check the new file in `backend/alembic/versions/` before you commit it. +## Formatting the backend + +Format the backend code before you commit. CI fails if it is unformatted: + +```bash +cd backend +python -m ruff format . +``` + ## Working on the project Branches, commits and pull requests: see [docs/git-workflow.md](docs/git-workflow.md). From b3fbf362a6b44e1fe6814ac51bfc2c298396a852 Mon Sep 17 00:00:00 2001 From: DarynaBb Date: Wed, 25 Nov 2026 15:18:58 +0100 Subject: [PATCH 2/2] style(api): format backend with ruff --- backend/alembic/env.py | 4 +- .../4444e762e7e3_create_entries_table.py | 58 ++++++---- .../e48cdf9dee35_create_users_table.py | 26 +++-- backend/app/config.py | 4 +- backend/app/dependencies.py | 3 +- backend/app/main.py | 1 - backend/app/models/__init__.py | 2 +- backend/app/models/entry.py | 5 +- backend/app/models/user.py | 3 +- backend/app/routers/auth.py | 12 +- backend/app/routers/entries.py | 22 ++-- backend/app/schemas/entry.py | 17 +-- backend/app/schemas/user.py | 1 + backend/tests/conftest.py | 2 +- backend/tests/test_entries.py | 109 ++++++------------ backend/tests/test_health.py | 1 - backend/tests/test_login.py | 13 +-- backend/tests/test_me.py | 13 +-- backend/tests/test_register.py | 11 +- backend/tests/test_security.py | 5 +- 20 files changed, 144 insertions(+), 168 deletions(-) diff --git a/backend/alembic/env.py b/backend/alembic/env.py index 508c66f..74c2a14 100644 --- a/backend/alembic/env.py +++ b/backend/alembic/env.py @@ -72,9 +72,7 @@ def run_migrations_online() -> None: ) with connectable.connect() as connection: - context.configure( - connection=connection, target_metadata=target_metadata - ) + context.configure(connection=connection, target_metadata=target_metadata) with context.begin_transaction(): context.run_migrations() diff --git a/backend/alembic/versions/4444e762e7e3_create_entries_table.py b/backend/alembic/versions/4444e762e7e3_create_entries_table.py index 6003ee0..9136959 100644 --- a/backend/alembic/versions/4444e762e7e3_create_entries_table.py +++ b/backend/alembic/versions/4444e762e7e3_create_entries_table.py @@ -5,6 +5,7 @@ Create Date: 2026-11-19 08:38:22.349963 """ + from collections.abc import Sequence import sqlalchemy as sa @@ -13,8 +14,8 @@ from alembic import op # revision identifiers, used by Alembic. -revision: str = '4444e762e7e3' -down_revision: str | Sequence[str] | None = 'e48cdf9dee35' +revision: str = "4444e762e7e3" +down_revision: str | Sequence[str] | None = "e48cdf9dee35" branch_labels: str | Sequence[str] | None = None depends_on: str | Sequence[str] | None = None @@ -22,34 +23,41 @@ def upgrade() -> None: """Upgrade schema.""" # ### commands auto generated by Alembic - please adjust! ### - op.create_table('entries', - sa.Column('id', sa.Integer(), nullable=False), - sa.Column('user_id', sa.Integer(), nullable=False), - sa.Column('kind', sqlmodel.sql.sqltypes.AutoString(), nullable=False), - sa.Column('amount', sa.Integer(), nullable=True), - sa.Column('entry_date', sa.Date(), nullable=False), - sa.Column('category', sqlmodel.sql.sqltypes.AutoString(), nullable=False), - sa.Column('note', sqlmodel.sql.sqltypes.AutoString(), nullable=True), - sa.Column('photo_path', sqlmodel.sql.sqltypes.AutoString(), nullable=True), - sa.Column('distance_km', sa.Integer(), nullable=True), - sa.Column('days', sa.Integer(), nullable=True), - sa.Column('created_at', sqlmodel.sql.sqltypes.UTCDateTime(), nullable=False), - sa.CheckConstraint("category IN ('uncategorized', 'work_equipment', 'literature', 'training', 'trips', 'other')", name='ck_entries_category'), - sa.CheckConstraint("kind IN ('receipt', 'trip')", name='ck_entries_kind'), - sa.ForeignKeyConstraint(['user_id'], ['users.id'], ), - sa.PrimaryKeyConstraint('id') + op.create_table( + "entries", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("user_id", sa.Integer(), nullable=False), + sa.Column("kind", sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column("amount", sa.Integer(), nullable=True), + sa.Column("entry_date", sa.Date(), nullable=False), + sa.Column("category", sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column("note", sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column("photo_path", sqlmodel.sql.sqltypes.AutoString(), nullable=True), + sa.Column("distance_km", sa.Integer(), nullable=True), + sa.Column("days", sa.Integer(), nullable=True), + sa.Column("created_at", sqlmodel.sql.sqltypes.UTCDateTime(), nullable=False), + sa.CheckConstraint( + "category IN ('uncategorized', 'work_equipment', 'literature', 'training', 'trips', 'other')", + name="ck_entries_category", + ), + sa.CheckConstraint("kind IN ('receipt', 'trip')", name="ck_entries_kind"), + sa.ForeignKeyConstraint( + ["user_id"], + ["users.id"], + ), + sa.PrimaryKeyConstraint("id"), ) - op.create_index(op.f('ix_entries_category'), 'entries', ['category'], unique=False) - op.create_index(op.f('ix_entries_kind'), 'entries', ['kind'], unique=False) - op.create_index(op.f('ix_entries_user_id'), 'entries', ['user_id'], unique=False) + op.create_index(op.f("ix_entries_category"), "entries", ["category"], unique=False) + op.create_index(op.f("ix_entries_kind"), "entries", ["kind"], unique=False) + op.create_index(op.f("ix_entries_user_id"), "entries", ["user_id"], unique=False) # ### end Alembic commands ### def downgrade() -> None: """Downgrade schema.""" # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f('ix_entries_user_id'), table_name='entries') - op.drop_index(op.f('ix_entries_kind'), table_name='entries') - op.drop_index(op.f('ix_entries_category'), table_name='entries') - op.drop_table('entries') + op.drop_index(op.f("ix_entries_user_id"), table_name="entries") + op.drop_index(op.f("ix_entries_kind"), table_name="entries") + op.drop_index(op.f("ix_entries_category"), table_name="entries") + op.drop_table("entries") # ### end Alembic commands ### diff --git a/backend/alembic/versions/e48cdf9dee35_create_users_table.py b/backend/alembic/versions/e48cdf9dee35_create_users_table.py index 3545fce..999d3be 100644 --- a/backend/alembic/versions/e48cdf9dee35_create_users_table.py +++ b/backend/alembic/versions/e48cdf9dee35_create_users_table.py @@ -1,10 +1,11 @@ """create users table Revision ID: e48cdf9dee35 -Revises: +Revises: Create Date: 2026-11-11 12:43:02.418363 """ + from collections.abc import Sequence import sqlalchemy as sa @@ -13,7 +14,7 @@ from alembic import op # revision identifiers, used by Alembic. -revision: str = 'e48cdf9dee35' +revision: str = "e48cdf9dee35" down_revision: str | Sequence[str] | None = None branch_labels: str | Sequence[str] | None = None depends_on: str | Sequence[str] | None = None @@ -22,21 +23,22 @@ def upgrade() -> None: """Upgrade schema.""" # ### commands auto generated by Alembic - please adjust! ### - op.create_table('users', - sa.Column('id', sa.Integer(), nullable=False), - sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False), - sa.Column('email', sqlmodel.sql.sqltypes.AutoString(), nullable=False), - sa.Column('password_hash', sqlmodel.sql.sqltypes.AutoString(), nullable=False), - sa.Column('created_at', sqlmodel.sql.sqltypes.UTCDateTime(), nullable=False), - sa.PrimaryKeyConstraint('id') + op.create_table( + "users", + sa.Column("id", sa.Integer(), nullable=False), + sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column("email", sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column("password_hash", sqlmodel.sql.sqltypes.AutoString(), nullable=False), + sa.Column("created_at", sqlmodel.sql.sqltypes.UTCDateTime(), nullable=False), + sa.PrimaryKeyConstraint("id"), ) - op.create_index(op.f('ix_users_email'), 'users', ['email'], unique=True) + op.create_index(op.f("ix_users_email"), "users", ["email"], unique=True) # ### end Alembic commands ### def downgrade() -> None: """Downgrade schema.""" # ### commands auto generated by Alembic - please adjust! ### - op.drop_index(op.f('ix_users_email'), table_name='users') - op.drop_table('users') + op.drop_index(op.f("ix_users_email"), table_name="users") + op.drop_table("users") # ### end Alembic commands ### diff --git a/backend/app/config.py b/backend/app/config.py index 7c7d380..7b77f99 100644 --- a/backend/app/config.py +++ b/backend/app/config.py @@ -14,9 +14,7 @@ JWT_SECRET = os.getenv("JWT_SECRET") if not JWT_SECRET or len(JWT_SECRET) < 32: - raise RuntimeError( - "JWT_SECRET must be set and contain at least 32 characters" - ) + raise RuntimeError("JWT_SECRET must be set and contain at least 32 characters") JWT_ALGORITHM = os.getenv("JWT_ALGORITHM", "HS256") JWT_EXPIRE_MINUTES = int(os.getenv("JWT_EXPIRE_MINUTES", "30")) diff --git a/backend/app/dependencies.py b/backend/app/dependencies.py index 2107d45..eb70d8f 100644 --- a/backend/app/dependencies.py +++ b/backend/app/dependencies.py @@ -38,7 +38,8 @@ def get_current_user( return user + CurrentUserDependency = Annotated[ User, Depends(get_current_user), -] \ No newline at end of file +] diff --git a/backend/app/main.py b/backend/app/main.py index 226ed55..6b2e821 100644 --- a/backend/app/main.py +++ b/backend/app/main.py @@ -21,4 +21,3 @@ @app.get("/health") def health(): return {"status": "ok"} - diff --git a/backend/app/models/__init__.py b/backend/app/models/__init__.py index c3c345e..6df6016 100644 --- a/backend/app/models/__init__.py +++ b/backend/app/models/__init__.py @@ -1,4 +1,4 @@ from .entry import Entry from .user import User -__all__ = ["Entry", "User"] \ No newline at end of file +__all__ = ["Entry", "User"] diff --git a/backend/app/models/entry.py b/backend/app/models/entry.py index 707bd44..f84d031 100644 --- a/backend/app/models/entry.py +++ b/backend/app/models/entry.py @@ -8,7 +8,10 @@ class Entry(SQLModel, table=True): __tablename__ = "entries" __table_args__ = ( CheckConstraint("kind IN ('receipt', 'trip')", name="ck_entries_kind"), - CheckConstraint("category IN ('uncategorized', 'work_equipment', 'literature', 'training', 'trips', 'other')", name="ck_entries_category") + CheckConstraint( + "category IN ('uncategorized', 'work_equipment', 'literature', 'training', 'trips', 'other')", + name="ck_entries_category", + ), ) id: int | None = Field(default=None, primary_key=True) diff --git a/backend/app/models/user.py b/backend/app/models/user.py index 59419d0..5e6c0a1 100644 --- a/backend/app/models/user.py +++ b/backend/app/models/user.py @@ -1,4 +1,3 @@ - from datetime import UTC, datetime from sqlmodel import Field, SQLModel @@ -11,4 +10,4 @@ class User(SQLModel, table=True): name: str = Field() email: str = Field(index=True, unique=True) password_hash: str - created_at: datetime = Field(default_factory=lambda: datetime.now(UTC)) \ No newline at end of file + created_at: datetime = Field(default_factory=lambda: datetime.now(UTC)) diff --git a/backend/app/routers/auth.py b/backend/app/routers/auth.py index 91b3c32..4d8734d 100644 --- a/backend/app/routers/auth.py +++ b/backend/app/routers/auth.py @@ -17,9 +17,7 @@ @router.post("/register", status_code=status.HTTP_201_CREATED) def register(user: UserRegister, session: SessionDependency): - existing_user = session.exec( - select(User).where(User.email == user.email) - ).first() + existing_user = session.exec(select(User).where(User.email == user.email)).first() if existing_user: raise HTTPException( @@ -43,11 +41,10 @@ def register(user: UserRegister, session: SessionDependency): "email": new_user.email, } + @router.post("/login") def login(user: UserLogin, session: SessionDependency): - existing_user = session.exec( - select(User).where(User.email == user.email) - ).first() + existing_user = session.exec(select(User).where(User.email == user.email)).first() if existing_user is not None: password_hash_to_check = existing_user.password_hash @@ -72,10 +69,11 @@ def login(user: UserLogin, session: SessionDependency): "token_type": "bearer", } + @router.get("/me") def get_me(current_user: CurrentUserDependency): return { "id": current_user.id, "name": current_user.name, "email": current_user.email, - } \ No newline at end of file + } diff --git a/backend/app/routers/entries.py b/backend/app/routers/entries.py index 63c22d3..29b9d5d 100644 --- a/backend/app/routers/entries.py +++ b/backend/app/routers/entries.py @@ -32,6 +32,7 @@ def get_own_entry_or_404( return entry + @router.post( "", response_model=EntryResponse, @@ -43,16 +44,17 @@ def create_entry( current_user: CurrentUserDependency, ): entry = Entry( - user_id=current_user.id, # ** entpackt Schlüssel und Werte zu benannten Argumenten - **entry_data.model_dump(), # (macht quasi kind = entry_data.kind, amount = entry_data.amount usw.) - ) # z.B. daten ={"kind"= receipt,} entry(**daten) -> entry (kind = receipt) - + user_id=current_user.id, # ** entpackt Schlüssel und Werte zu benannten Argumenten + **entry_data.model_dump(), # (macht quasi kind = entry_data.kind, amount = entry_data.amount usw.) + ) # z.B. daten ={"kind"= receipt,} entry(**daten) -> entry (kind = receipt) + session.add(entry) session.commit() session.refresh(entry) return entry + @router.get( "", response_model=list[EntryResponse], @@ -61,12 +63,11 @@ def list_entries( session: SessionDependency, current_user: CurrentUserDependency, ): - entries = session.exec( - select(Entry).where(Entry.user_id == current_user.id) - ).all() + entries = session.exec(select(Entry).where(Entry.user_id == current_user.id)).all() return entries + @router.get( "/{entry_id}", response_model=EntryResponse, @@ -82,6 +83,7 @@ def get_entry( current_user, ) + @router.patch( "/{entry_id}", response_model=EntryResponse, @@ -98,7 +100,9 @@ def update_entry( current_user, ) - update_data = entry_data.model_dump(exclude_unset=True) #exclude_unset=True gibt nur die vom Client tatsächlich mitgeschickten Felder aus + update_data = entry_data.model_dump( + exclude_unset=True + ) # exclude_unset=True gibt nur die vom Client tatsächlich mitgeschickten Felder aus for field, value in update_data.items(): setattr(entry, field, value) @@ -109,6 +113,7 @@ def update_entry( return entry + @router.delete( "/{entry_id}", status_code=status.HTTP_204_NO_CONTENT, @@ -126,4 +131,3 @@ def delete_entry( session.delete(entry) session.commit() - \ No newline at end of file diff --git a/backend/app/schemas/entry.py b/backend/app/schemas/entry.py index ca6de35..b2f9732 100644 --- a/backend/app/schemas/entry.py +++ b/backend/app/schemas/entry.py @@ -6,14 +6,15 @@ EntryKind = Literal["receipt", "trip"] EntryCategory = Literal[ - "uncategorized", - "work_equipment", - "literature", - "training", - "trips", - "other", + "uncategorized", + "work_equipment", + "literature", + "training", + "trips", + "other", ] + class EntryCreate(BaseModel): kind: EntryKind = "receipt" amount: int | None = Field(default=None, ge=0) @@ -23,6 +24,7 @@ class EntryCreate(BaseModel): distance_km: int | None = Field(default=None, ge=0) days: int | None = Field(default=None, ge=0) + class EntryUpdate(BaseModel): kind: EntryKind | None = None amount: int | None = Field(default=None, ge=0) @@ -39,6 +41,7 @@ def not_null(cls, value): raise ValueError("must not be null") return value + class EntryResponse(BaseModel): id: int kind: EntryKind @@ -48,4 +51,4 @@ class EntryResponse(BaseModel): note: str | None distance_km: int | None days: int | None - created_at: datetime \ No newline at end of file + created_at: datetime diff --git a/backend/app/schemas/user.py b/backend/app/schemas/user.py index ee4570d..929eee4 100644 --- a/backend/app/schemas/user.py +++ b/backend/app/schemas/user.py @@ -14,5 +14,6 @@ class UserRegister(EmailSchema): name: str = Field(min_length=2, max_length=50) password: str = Field(min_length=8, max_length=128) + class UserLogin(EmailSchema): password: str = Field(min_length=1, max_length=128) diff --git a/backend/tests/conftest.py b/backend/tests/conftest.py index 755c98e..cd62116 100644 --- a/backend/tests/conftest.py +++ b/backend/tests/conftest.py @@ -32,4 +32,4 @@ def get_test_session(): yield test_client app.dependency_overrides.clear() - SQLModel.metadata.drop_all(test_engine) \ No newline at end of file + SQLModel.metadata.drop_all(test_engine) diff --git a/backend/tests/test_entries.py b/backend/tests/test_entries.py index 048691c..ff6fcda 100644 --- a/backend/tests/test_entries.py +++ b/backend/tests/test_entries.py @@ -28,6 +28,7 @@ def create_user_and_login(client: TestClient, name: str, email: str) -> str: return login_response.json()["access_token"] + def test_create_entry(client): access_token = create_user_and_login(client, "Illia", "illia@example.com") @@ -39,9 +40,7 @@ def test_create_entry(client): "category": "work_equipment", "note": "USB-C Adapter", }, - headers={ - "Authorization": f"Bearer {access_token}" - }, + headers={"Authorization": f"Bearer {access_token}"}, ) assert response.status_code == 201 @@ -57,6 +56,7 @@ def test_create_entry(client): assert "user_id" not in data assert "photo_path" not in data + def test_create_entry_without_token(client): response = client.post( "/entries", @@ -69,6 +69,7 @@ def test_create_entry_without_token(client): assert response.status_code == 401 + def test_list_entries_only_returns_own_entries(client): illia_token = create_user_and_login( client, @@ -90,9 +91,7 @@ def test_list_entries_only_returns_own_entries(client): "category": "work_equipment", "note": "Illias Entry", }, - headers={ - "Authorization": f"Bearer {illia_token}" - }, + headers={"Authorization": f"Bearer {illia_token}"}, ) assert illia_entry.status_code == 201 @@ -105,18 +104,14 @@ def test_list_entries_only_returns_own_entries(client): "category": "literature", "note": "Andreas Entry", }, - headers={ - "Authorization": f"Bearer {andreas_token}" - }, + headers={"Authorization": f"Bearer {andreas_token}"}, ) assert andreas_entry.status_code == 201 response = client.get( "/entries", - headers={ - "Authorization": f"Bearer {illia_token}" - }, + headers={"Authorization": f"Bearer {illia_token}"}, ) assert response.status_code == 200 @@ -127,6 +122,7 @@ def test_list_entries_only_returns_own_entries(client): assert entries[0]["amount"] == 1999 assert entries[0]["note"] == "Illias Entry" + def test_get_own_entry(client: TestClient): access_token = create_user_and_login( client, @@ -141,9 +137,7 @@ def test_get_own_entry(client: TestClient): "amount": 1999, "category": "work_equipment", }, - headers={ - "Authorization": f"Bearer {access_token}" - }, + headers={"Authorization": f"Bearer {access_token}"}, ) assert create_response.status_code == 201 @@ -152,15 +146,14 @@ def test_get_own_entry(client: TestClient): response = client.get( f"/entries/{entry_id}", - headers={ - "Authorization": f"Bearer {access_token}" - }, + headers={"Authorization": f"Bearer {access_token}"}, ) assert response.status_code == 200 assert response.json()["id"] == entry_id assert response.json()["amount"] == 1999 + def test_get_other_users_entry_returns_404(client: TestClient): illia_token = create_user_and_login( client, @@ -181,9 +174,7 @@ def test_get_other_users_entry_returns_404(client: TestClient): "amount": 1999, "category": "work_equipment", }, - headers={ - "Authorization": f"Bearer {illia_token}" - }, + headers={"Authorization": f"Bearer {illia_token}"}, ) assert create_response.status_code == 201 @@ -192,15 +183,12 @@ def test_get_other_users_entry_returns_404(client: TestClient): response = client.get( f"/entries/{entry_id}", - headers={ - "Authorization": f"Bearer {andreas_token}" - }, + headers={"Authorization": f"Bearer {andreas_token}"}, ) assert response.status_code == 404 - assert response.json() == { - "detail": "Entry not found" - } + assert response.json() == {"detail": "Entry not found"} + def test_update_own_entry(client: TestClient): access_token = create_user_and_login( @@ -217,9 +205,7 @@ def test_update_own_entry(client: TestClient): "category": "work_equipment", "note": "Alte Notiz", }, - headers={ - "Authorization": f"Bearer {access_token}" - }, + headers={"Authorization": f"Bearer {access_token}"}, ) assert create_response.status_code == 201 @@ -232,9 +218,7 @@ def test_update_own_entry(client: TestClient): "amount": 2499, "note": "Neue Notiz", }, - headers={ - "Authorization": f"Bearer {access_token}" - }, + headers={"Authorization": f"Bearer {access_token}"}, ) assert response.status_code == 200 @@ -245,6 +229,7 @@ def test_update_own_entry(client: TestClient): assert data["note"] == "Neue Notiz" assert data["category"] == "work_equipment" + def test_update_other_users_entry_returns_404(client: TestClient): illia_token = create_user_and_login( client, @@ -265,9 +250,7 @@ def test_update_other_users_entry_returns_404(client: TestClient): "amount": 1999, "category": "work_equipment", }, - headers={ - "Authorization": f"Bearer {illia_token}" - }, + headers={"Authorization": f"Bearer {illia_token}"}, ) assert create_response.status_code == 201 @@ -279,15 +262,12 @@ def test_update_other_users_entry_returns_404(client: TestClient): json={ "amount": 999999, }, - headers={ - "Authorization": f"Bearer {andreas_token}" - }, + headers={"Authorization": f"Bearer {andreas_token}"}, ) assert response.status_code == 404 - assert response.json() == { - "detail": "Entry not found" - } + assert response.json() == {"detail": "Entry not found"} + def test_delete_own_entry(client: TestClient): access_token = create_user_and_login( @@ -303,9 +283,7 @@ def test_delete_own_entry(client: TestClient): "amount": 1999, "category": "work_equipment", }, - headers={ - "Authorization": f"Bearer {access_token}" - }, + headers={"Authorization": f"Bearer {access_token}"}, ) assert create_response.status_code == 201 @@ -314,22 +292,19 @@ def test_delete_own_entry(client: TestClient): delete_response = client.delete( f"/entries/{entry_id}", - headers={ - "Authorization": f"Bearer {access_token}" - }, + headers={"Authorization": f"Bearer {access_token}"}, ) assert delete_response.status_code == 204 get_response = client.get( f"/entries/{entry_id}", - headers={ - "Authorization": f"Bearer {access_token}" - }, + headers={"Authorization": f"Bearer {access_token}"}, ) assert get_response.status_code == 404 + def test_delete_other_users_entry_returns_404(client: TestClient): illia_token = create_user_and_login( client, @@ -350,9 +325,7 @@ def test_delete_other_users_entry_returns_404(client: TestClient): "amount": 1999, "category": "work_equipment", }, - headers={ - "Authorization": f"Bearer {illia_token}" - }, + headers={"Authorization": f"Bearer {illia_token}"}, ) assert create_response.status_code == 201 @@ -361,22 +334,19 @@ def test_delete_other_users_entry_returns_404(client: TestClient): delete_response = client.delete( f"/entries/{entry_id}", - headers={ - "Authorization": f"Bearer {andreas_token}" - }, + headers={"Authorization": f"Bearer {andreas_token}"}, ) assert delete_response.status_code == 404 get_response = client.get( f"/entries/{entry_id}", - headers={ - "Authorization": f"Bearer {illia_token}" - }, + headers={"Authorization": f"Bearer {illia_token}"}, ) assert get_response.status_code == 200 + @pytest.mark.parametrize( "field", ["kind", "category", "entry_date"], @@ -398,9 +368,7 @@ def test_update_entry_rejects_null_required_fields( "amount": 1999, "category": "work_equipment", }, - headers={ - "Authorization": f"Bearer {access_token}" - }, + headers={"Authorization": f"Bearer {access_token}"}, ) assert create_response.status_code == 201 @@ -412,13 +380,12 @@ def test_update_entry_rejects_null_required_fields( json={ field: None, }, - headers={ - "Authorization": f"Bearer {access_token}" - }, + headers={"Authorization": f"Bearer {access_token}"}, ) assert response.status_code == 422 + @pytest.mark.parametrize( "field", ["amount", "note", "distance_km", "days"], @@ -443,9 +410,7 @@ def test_update_entry_allows_null_optional_fields( "distance_km": 20, "days": 2, }, - headers={ - "Authorization": f"Bearer {access_token}" - }, + headers={"Authorization": f"Bearer {access_token}"}, ) assert create_response.status_code == 201 @@ -457,10 +422,8 @@ def test_update_entry_allows_null_optional_fields( json={ field: None, }, - headers={ - "Authorization": f"Bearer {access_token}" - }, + headers={"Authorization": f"Bearer {access_token}"}, ) assert response.status_code == 200 - assert response.json()[field] is None \ No newline at end of file + assert response.json()[field] is None diff --git a/backend/tests/test_health.py b/backend/tests/test_health.py index c7596ce..abfde7e 100644 --- a/backend/tests/test_health.py +++ b/backend/tests/test_health.py @@ -3,4 +3,3 @@ def test_health(client): assert response.status_code == 200 assert response.json() == {"status": "ok"} - \ No newline at end of file diff --git a/backend/tests/test_login.py b/backend/tests/test_login.py index 3ec85c0..c9a1cb8 100644 --- a/backend/tests/test_login.py +++ b/backend/tests/test_login.py @@ -34,6 +34,7 @@ def test_login_success(client): assert token_user_id == user_id + def test_login_wrong_password(client): register_response = client.post( "/register", @@ -55,9 +56,8 @@ def test_login_wrong_password(client): ) assert response.status_code == 401 - assert response.json() == { - "detail": "Invalid email or password" - } + assert response.json() == {"detail": "Invalid email or password"} + def test_login_unknown_email(client): response = client.post( @@ -69,9 +69,8 @@ def test_login_unknown_email(client): ) assert response.status_code == 401 - assert response.json() == { - "detail": "Invalid email or password" - } + assert response.json() == {"detail": "Invalid email or password"} + def test_login_email_is_case_insensitive(client): register_response = client.post( @@ -93,4 +92,4 @@ def test_login_email_is_case_insensitive(client): }, ) - assert login_response.status_code == 200 \ No newline at end of file + assert login_response.status_code == 200 diff --git a/backend/tests/test_me.py b/backend/tests/test_me.py index f4023f2..ebd32a2 100644 --- a/backend/tests/test_me.py +++ b/backend/tests/test_me.py @@ -26,9 +26,7 @@ def test_me_success(client): response = client.get( "/me", - headers={ - "Authorization": f"Bearer {access_token}" - }, + headers={"Authorization": f"Bearer {access_token}"}, ) assert response.status_code == 200 @@ -39,15 +37,12 @@ def test_me_success(client): assert data["name"] == "Illia" assert data["email"] == "illia@example.com" + def test_me_invalid_token(client): response = client.get( "/me", - headers={ - "Authorization": "Bearer das-ist-kein-gueltiger-token" - }, + headers={"Authorization": "Bearer das-ist-kein-gueltiger-token"}, ) assert response.status_code == 401 - assert response.json() == { - "detail": "Invalid or expired token" - } \ No newline at end of file + assert response.json() == {"detail": "Invalid or expired token"} diff --git a/backend/tests/test_register.py b/backend/tests/test_register.py index 39fa713..c72c5bc 100644 --- a/backend/tests/test_register.py +++ b/backend/tests/test_register.py @@ -18,6 +18,7 @@ def test_register_success(client): assert "password" not in data assert "password_hash" not in data + def test_register_duplicate_email(client): user_data = { "name": "Illia", @@ -30,9 +31,8 @@ def test_register_duplicate_email(client): assert first_response.status_code == 201 assert second_response.status_code == 409 - assert second_response.json() == { - "detail": "Email already registered" - } + assert second_response.json() == {"detail": "Email already registered"} + def test_register_invalid_email(client): response = client.post( @@ -46,6 +46,7 @@ def test_register_invalid_email(client): assert response.status_code == 422 + def test_register_password_too_short(client): response = client.post( "/register", @@ -58,6 +59,7 @@ def test_register_password_too_short(client): assert response.status_code == 422 + def test_register_normalizes_email(client): response = client.post( "/register", @@ -71,6 +73,7 @@ def test_register_normalizes_email(client): assert response.status_code == 201 assert response.json()["email"] == "illia@example.com" + def test_register_rejects_duplicate_email_with_different_case(client): first_response = client.post( "/register", @@ -92,4 +95,4 @@ def test_register_rejects_duplicate_email_with_different_case(client): }, ) - assert second_response.status_code == 409 \ No newline at end of file + assert second_response.status_code == 409 diff --git a/backend/tests/test_security.py b/backend/tests/test_security.py index 9845f5b..34cea6a 100644 --- a/backend/tests/test_security.py +++ b/backend/tests/test_security.py @@ -16,6 +16,7 @@ def test_hash_password(): assert hashed_password != password + def test_verify_password(): password = "meinSicheresPasswort123" hashed_password = hash_password(password) @@ -23,6 +24,7 @@ def test_verify_password(): assert verify_password(password, hashed_password) is True assert verify_password("falschesPasswort", hashed_password) is False + def test_access_token(): user_id = 42 @@ -31,10 +33,11 @@ def test_access_token(): assert decoded_user_id == user_id + def test_invalid_access_token(): token = create_access_token(42) manipulated_token = token + "abc" with pytest.raises(jwt.InvalidTokenError): - decode_access_token(manipulated_token) \ No newline at end of file + decode_access_token(manipulated_token)