🐛 Handle non-existing user IDs in read_user_by_id (#1396)

Co-authored-by: Motov Yurii <109919500+YuriiMotov@users.noreply.github.com>
This commit is contained in:
Saltie
2026-01-22 13:37:57 +01:00
committed by GitHub
parent fe3bafc6f6
commit 4cab9e972f
2 changed files with 35 additions and 3 deletions

View File

@@ -170,6 +170,8 @@ def read_user_by_id(
status_code=403,
detail="The user doesn't have enough privileges",
)
if user is None:
raise HTTPException(status_code=404, detail="User not found")
return user

View File

@@ -8,6 +8,7 @@ from app import crud
from app.core.config import settings
from app.core.security import verify_password
from app.models import User, UserCreate
from tests.utils.user import create_random_user
from tests.utils.utils import random_email, random_lower_string
@@ -56,7 +57,7 @@ def test_create_user_new_email(
assert user.email == created_user["email"]
def test_get_existing_user(
def test_get_existing_user_as_superuser(
client: TestClient, superuser_token_headers: dict[str, str], db: Session
) -> None:
username = random_email()
@@ -75,6 +76,17 @@ def test_get_existing_user(
assert existing_user.email == api_user["email"]
def test_get_non_existing_user_as_superuser(
client: TestClient, superuser_token_headers: dict[str, str]
) -> None:
r = client.get(
f"{settings.API_V1_STR}/users/{uuid.uuid4()}",
headers=superuser_token_headers,
)
assert r.status_code == 404
assert r.json() == {"detail": "User not found"}
def test_get_existing_user_current_user(client: TestClient, db: Session) -> None:
username = random_email()
password = random_lower_string()
@@ -103,10 +115,28 @@ def test_get_existing_user_current_user(client: TestClient, db: Session) -> None
def test_get_existing_user_permissions_error(
client: TestClient, normal_user_token_headers: dict[str, str]
db: Session,
client: TestClient,
normal_user_token_headers: dict[str, str],
) -> None:
user = create_random_user(db)
r = client.get(
f"{settings.API_V1_STR}/users/{uuid.uuid4()}",
f"{settings.API_V1_STR}/users/{user.id}",
headers=normal_user_token_headers,
)
assert r.status_code == 403
assert r.json() == {"detail": "The user doesn't have enough privileges"}
def test_get_non_existing_user_permissions_error(
client: TestClient,
normal_user_token_headers: dict[str, str],
) -> None:
user_id = uuid.uuid4()
r = client.get(
f"{settings.API_V1_STR}/users/{user_id}",
headers=normal_user_token_headers,
)
assert r.status_code == 403