Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 19 additions & 0 deletions backend/app/api/routes/items.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,25 @@ def read_items(
return ItemsPublic(data=items_public, count=count)


@router.get("/count")
def read_items_count(
session: SessionDep, current_user: CurrentUser
) -> Any:
"""
Retrieve total item count.
"""
if current_user.is_superuser:
count_statement = select(func.count()).select_from(Item)
else:
count_statement = (
select(func.count())
.select_from(Item)
.where(Item.owner_id == current_user.id)
)
count = session.exec(count_statement).one()
return {"count": count}


@router.get("/{id}", response_model=ItemPublic)
def read_item(session: SessionDep, current_user: CurrentUser, id: uuid.UUID) -> Any:
"""
Expand Down
39 changes: 38 additions & 1 deletion backend/tests/api/routes/test_items.py
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import uuid

from fastapi.testclient import TestClient
from sqlmodel import Session
from sqlmodel import Session, delete

from app.core.config import settings
from app.core.db import engine
from app.models import Item
from tests.utils.item import create_random_item


Expand Down Expand Up @@ -162,3 +164,38 @@ def test_delete_item_not_enough_permissions(
assert response.status_code == 403
content = response.json()
assert content["detail"] == "Not enough permissions"


def test_read_items_count(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
# Create some items first
create_random_item(db)
create_random_item(db)

response = client.get(
f"{settings.API_V1_STR}/items/count",
headers=superuser_token_headers,
)
assert response.status_code == 200
content = response.json()
assert "count" in content
assert content["count"] >= 2


def test_read_items_count_zero(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
# Clear all items first
statement = delete(Item)
db.execute(statement)
db.commit()

response = client.get(
f"{settings.API_V1_STR}/items/count",
headers=superuser_token_headers,
)
assert response.status_code == 200
content = response.json()
assert "count" in content
assert content["count"] == 0
Loading