Skip to content

Commit f91a7fa

Browse files
updates
1 parent 163e0c1 commit f91a7fa

File tree

5 files changed

+68
-26
lines changed

5 files changed

+68
-26
lines changed

.python-version

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
3.12.2

app/schemas.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,10 +1,13 @@
1+
from enum import Enum
12
from datetime import datetime
23
from typing import List
34
from pydantic import BaseModel, Field
5+
from uuid import uuid4, UUID
46

57

68
class UserBaseSchema(BaseModel):
7-
id: str | None = None
9+
10+
id: UUID | None = None
811
first_name: str = Field(
912
..., description="The first name of the user", example="John"
1013
)
@@ -24,3 +27,13 @@ class ListUserResponse(BaseModel):
2427
status: str
2528
results: int
2629
users: List[UserBaseSchema]
30+
31+
32+
class Status(Enum):
33+
Success = "Success"
34+
Failed = "Failed"
35+
36+
37+
class CreateUserResponse(BaseModel):
38+
Status: Status
39+
User: UserBaseSchema

app/user.py

Lines changed: 34 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,11 +1,45 @@
11
import app.schemas as schemas, app.models as models
22
from sqlalchemy.orm import Session
3+
from sqlalchemy.exc import IntegrityError
4+
from pydantic import ValidationError
35
from fastapi import Depends, HTTPException, status, APIRouter
46
from app.database import get_db
57

68
router = APIRouter()
79

810

11+
@router.post(
12+
"/", status_code=status.HTTP_201_CREATED, response_model=schemas.CreateUserResponse
13+
)
14+
def create_user(payload: schemas.UserBaseSchema, db: Session = Depends(get_db)):
15+
try:
16+
# Create a new user instance from the payload
17+
new_user = models.User(**payload.dict())
18+
db.add(new_user)
19+
db.commit()
20+
db.refresh(new_user)
21+
22+
except IntegrityError as e:
23+
db.rollback()
24+
# Log the error or handle it as needed
25+
raise HTTPException(
26+
status_code=status.HTTP_409_CONFLICT,
27+
detail="A user with the given details already exists.",
28+
) from e
29+
except Exception as e:
30+
db.rollback()
31+
# Handle other types of database errors
32+
raise HTTPException(
33+
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
34+
detail="An error occurred while creating the user.",
35+
) from e
36+
37+
# Convert the SQLAlchemy model instance to a Pydantic model
38+
user_schema = schemas.UserBaseSchema.from_orm(new_user)
39+
# Return the successful creation response
40+
return schemas.CreateUserResponse(Status=schemas.Status.Success, User=user_schema)
41+
42+
943
@router.get("/", status_code=status.HTTP_200_OK)
1044
def get_users(
1145
db: Session = Depends(get_db), limit: int = 10, page: int = 1, search: str = ""
@@ -22,15 +56,6 @@ def get_users(
2256
return {"Status": "Success", "Results": len(users), "Users": users}
2357

2458

25-
@router.post("/", status_code=status.HTTP_201_CREATED)
26-
def create_user(payload: schemas.UserBaseSchema, db: Session = Depends(get_db)):
27-
new_user = models.User(**payload.dict())
28-
db.add(new_user)
29-
db.commit()
30-
db.refresh(new_user)
31-
return {"Status": "Success", "User": new_user}
32-
33-
3459
@router.patch("/{userId}", status_code=status.HTTP_202_ACCEPTED)
3560
def update_user(
3661
userId: str, payload: schemas.UserBaseSchema, db: Session = Depends(get_db)

tests/conftest.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -11,18 +11,16 @@ def test_client():
1111

1212

1313
@pytest.fixture
14-
def user_id(scope="session"):
14+
def user_id():
1515
"""Generate a random user id."""
1616
return str(uuid.uuid4())
1717

1818

1919
@pytest.fixture
20-
def user_payload(user_id):
20+
def user_payload():
2121
"""Generate a user payload."""
2222
return {
23-
"id": user_id,
2423
"first_name": "PLACEHOLDER",
2524
"last_name": "PLACEHOLDER",
2625
"address": "PLACEHOLDER",
27-
"createdAt": "2024-04-30T16:39:23",
2826
}

tests/test_crud_api.py

Lines changed: 17 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -7,18 +7,23 @@ def test_root(test_client):
77
def test_create_user_success(test_client, user_payload, user_id):
88
response = test_client.post("/api/users/", json=user_payload)
99
assert response.status_code == 201
10-
assert response.json() == {
11-
"Status": "Success",
12-
"User": {
13-
"id": user_id,
14-
"activated": False,
15-
"createdAt": "2024-04-30T16:39:23",
16-
"first_name": "PLACEHOLDER",
17-
"last_name": "PLACEHOLDER",
18-
"address": "PLACEHOLDER",
19-
"updatedAt": None,
20-
},
21-
}
10+
assert response.json()["Status"] == "Success"
11+
assert response.json()["User"]["address"] == "PLACEHOLDER"
12+
assert response.json()["User"]["first_name"] == "PLACEHOLDER"
13+
assert response.json()["User"]["last_name"] == "PLACEHOLDER"
14+
15+
# assert response.json() == {
16+
# "Status": "Success",
17+
# "User": {
18+
# "id": user_id,
19+
# "activated": False,
20+
# "createdAt": "2024-04-30T16:39:23",
21+
# "first_name": "PLACEHOLDER",
22+
# "last_name": "PLACEHOLDER",
23+
# "address": "PLACEHOLDER",
24+
# "updatedAt": None,
25+
# },
26+
# }
2227

2328

2429
# def test_create_user_fail(test_client, user_payload, user_id):

0 commit comments

Comments
 (0)