Skip to content

Commit

Permalink
Add unit tests for patient highlight
Browse files Browse the repository at this point in the history
  • Loading branch information
weikangg committed Jan 5, 2025
1 parent 7d708fa commit e0298fe
Show file tree
Hide file tree
Showing 19 changed files with 338 additions and 113 deletions.
4 changes: 2 additions & 2 deletions app/crud/allergy_reaction_type_crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,13 @@


def get_all_reaction_types(db: Session):
return db.query(AllergyReactionType).all()
return db.query(AllergyReactionType).filter(AllergyReactionType.IsDeleted == "0").all()


def get_reaction_type_by_id(db: Session, allergy_reaction_type_id: int):
return (
db.query(AllergyReactionType)
.filter(AllergyReactionType.AllergyReactionTypeID == allergy_reaction_type_id)
.filter(AllergyReactionType.AllergyReactionTypeID == allergy_reaction_type_id, AllergyReactionType.IsDeleted == "0")
.first()
)

Expand Down
5 changes: 2 additions & 3 deletions app/crud/allergy_type_crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,17 +5,16 @@


def get_all_allergy_types(db: Session):
return db.query(AllergyType).all()
return db.query(AllergyType).filter(AllergyType.IsDeleted == "0").all()


def get_allergy_type_by_id(db: Session, allergy_type_id: int):
return (
db.query(AllergyType)
.filter(AllergyType.AllergyTypeID == allergy_type_id)
.filter(AllergyType.AllergyTypeID == allergy_type_id,AllergyType.IsDeleted == "0")
.first()
)


def create_allergy_type(db: Session, allergy_type: AllergyTypeCreate, created_by: int):
db_allergy_type = AllergyType(
**allergy_type.model_dump(), CreatedById=created_by, ModifiedById=created_by
Expand Down
4 changes: 2 additions & 2 deletions app/crud/patient_allergy_mapping_crud.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,7 @@ def get_all_allergies(db: Session):
.all()
)

# Handle "Active" logic
# Filter soft deleted entries
patient_allergies = []
for result in results:
allergy_type_value = (
Expand Down Expand Up @@ -96,7 +96,7 @@ def get_patient_allergies(db: Session, patient_id: int):
.all()
)

# Handle "Active" logic
# Filter soft deleted entries
patient_allergies = []
for result in results:
allergy_type_value = (
Expand Down
60 changes: 38 additions & 22 deletions app/crud/patient_highlight_crud.py
Original file line number Diff line number Diff line change
@@ -1,35 +1,51 @@
from sqlalchemy.orm import Session
from ..models.patient_highlight_model import PatientHighlight
from ..schemas.patient_highlight import HighlightCreate, HighlightUpdate
from ..schemas.patient_highlight import PatientHighlightCreate, PatientHighlightUpdate
from datetime import datetime
from fastapi import HTTPException

def get_highlights(db: Session, skip: int = 0, limit: int = 100):
return db.query(PatientHighlight).order_by(PatientHighlight.id).offset(skip).limit(limit).all()
def get_all_highlights(db: Session):
return db.query(PatientHighlight).filter(PatientHighlight.IsDeleted == "0").all()

def get_highlight(db: Session, highlight_id: int):
return db.query(PatientHighlight).filter(PatientHighlight.id == highlight_id).first()
def get_highlights_by_patient(db: Session, patient_id: int):
return (
db.query(PatientHighlight)
.filter(PatientHighlight.PatientId == patient_id, PatientHighlight.IsDeleted == "0")
.all()
)

def get_highlights_grouped_by_patient(db: Session):
return db.query(PatientHighlight).all() # Adjust this query as needed to group by patient_id

def create_highlight(db: Session, highlight: HighlightCreate):
db_highlight = PatientHighlight(**highlight.dict())
def create_highlight(db: Session, highlight_data: PatientHighlightCreate, created_by: int):
db_highlight = PatientHighlight(
**highlight_data.dict(), CreatedById=created_by, ModifiedById=created_by
)
db.add(db_highlight)
db.commit()
db.refresh(db_highlight)
return db_highlight

def update_highlight(db: Session, highlight_id: int, highlight: HighlightUpdate):
db_highlight = db.query(PatientHighlight).filter(PatientHighlight.id == highlight_id).first()
if db_highlight:
for key, value in highlight.dict().items():
setattr(db_highlight, key, value)
db.commit()
db.refresh(db_highlight)
def update_highlight(db: Session, highlight_id: int, highlight_data: PatientHighlightUpdate, modified_by: int):
db_highlight = db.query(PatientHighlight).filter(PatientHighlight.Id == highlight_id).first()

if not db_highlight or db_highlight.IsDeleted == "1":
raise HTTPException(status_code=404, detail="Highlight not found")

for key, value in highlight_data.dict(exclude_unset=True).items():
setattr(db_highlight, key, value)

db_highlight.ModifiedDate = datetime.now()
db_highlight.ModifiedById = modified_by
db.commit()
db.refresh(db_highlight)
return db_highlight

def delete_highlight(db: Session, highlight_id: int):
db_highlight = db.query(PatientHighlight).filter(PatientHighlight.id == highlight_id).first()
if db_highlight:
db.delete(db_highlight)
db.commit()
def delete_highlight(db: Session, highlight_id: int, modified_by: int):
db_highlight = db.query(PatientHighlight).filter(PatientHighlight.Id == highlight_id).first()

if not db_highlight or db_highlight.IsDeleted == "1":
raise HTTPException(status_code=404, detail="Highlight not found")

db_highlight.IsDeleted = "1"
db_highlight.ModifiedDate = datetime.now()
db_highlight.ModifiedById = modified_by
db.commit()
return db_highlight
32 changes: 16 additions & 16 deletions app/models/patient_highlight_model.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,22 @@
from sqlalchemy import Column, Integer, String, DateTime, ForeignKey
from sqlalchemy import Column, Integer, String, DateTime,ForeignKey
from sqlalchemy.orm import relationship
from datetime import datetime, timezone

from datetime import datetime
from app.database import Base

class PatientHighlight(Base):
__tablename__ = "PATIENT_HIGHLIGHT"

id = Column(Integer, primary_key=True, index=True) # Changed to Integer
active = Column(String(1), default='Y', nullable=False) # used to check if record is active or not, substitute isDeleted column
patientId = Column(Integer, ForeignKey('PATIENT.id')) # Changed to Integer
type = Column(String(255))
highlightJSON = Column(String(255)) # Consider changing to Text if this is meant to store JSON data
startDate = Column(DateTime)
endDate = Column(DateTime)

createdDate = Column(DateTime, nullable=False, default=DateTime)
modifiedDate = Column(DateTime, nullable=False, default=DateTime)
createdById = Column(Integer, nullable=False) # Changed to Integer
modifiedById = Column(Integer, nullable=False) # Changed to Integer

patient = relationship("Patient", back_populates="highlights")
Id = Column(Integer, primary_key=True, index=True)
IsDeleted = Column(String(1), default="0", nullable=False)
PatientId = Column(Integer, ForeignKey("PATIENT.id"), nullable=False)
Type = Column(String(255), nullable=False)
HighlightJSON = Column(String(255), nullable=False)
StartDate = Column(DateTime, nullable=False)
EndDate = Column(DateTime, nullable=False)
CreatedDate = Column(DateTime, nullable=False, default=datetime.now)
ModifiedDate = Column(DateTime, nullable=False, default=datetime.now)
CreatedById = Column(Integer, nullable=False, default=1)
ModifiedById = Column(Integer, nullable=False, default=1)

patient = relationship("Patient", back_populates="highlights")
66 changes: 36 additions & 30 deletions app/routers/patient_highlight_router.py
Original file line number Diff line number Diff line change
@@ -1,40 +1,46 @@
from fastapi import APIRouter, Depends, HTTPException
from sqlalchemy.orm import Session
from ..database import get_db
from ..crud import patient_highlight_crud as crud_highlight
from ..schemas import patient_highlight as schemas_highlight
from ..crud.patient_highlight_crud import (
get_all_highlights,
get_highlights_by_patient,
create_highlight,
update_highlight,
delete_highlight,
)
from ..schemas.patient_highlight import (
PatientHighlight,
PatientHighlightCreate,
PatientHighlightUpdate,
)

router = APIRouter()

@router.get("/Highlight/list", response_model=list[schemas_highlight.Highlight])
def get_highlights_grouped_by_patient(db: Session = Depends(get_db)):
return crud_highlight.get_highlights_grouped_by_patient(db)
@router.get("/get_all_highlights", response_model=list[PatientHighlight], description="Get all highlights.")
def get_all_patient_highlights(db: Session = Depends(get_db)):
return get_all_highlights(db)

@router.get("/Highlight", response_model=list[schemas_highlight.Highlight])
def get_highlights(skip: int = 0, limit: int = 100, db: Session = Depends(get_db)):
return crud_highlight.get_highlights(db, skip=skip, limit=limit)
@router.get("/get_highlights_by_patient/{patient_id}", response_model=list[PatientHighlight], description="Get highlights by patient ID.")
def get_patient_highlights(patient_id: int, db: Session = Depends(get_db)):
highlights = get_highlights_by_patient(db, patient_id)
if not highlights:
raise HTTPException(status_code=404, detail="No highlights found for the patient")
return highlights

@router.get("/Highlight/{highlight_id}", response_model=schemas_highlight.Highlight)
def get_highlight(highlight_id: int, db: Session = Depends(get_db)):
db_highlight = crud_highlight.get_highlight(db, highlight_id)
if not db_highlight:
raise HTTPException(status_code=404, detail="Highlight not found")
return db_highlight
@router.post("/create_highlight", response_model=PatientHighlight, description="Create a new highlight.")
def create_patient_highlight(highlight_data: PatientHighlightCreate, db: Session = Depends(get_db)):
# Replace with actual user ID in a real-world scenario
created_by = 1
return create_highlight(db, highlight_data, created_by)

@router.post("/Highlight/add", response_model=schemas_highlight.Highlight)
def create_highlight(highlight: schemas_highlight.HighlightCreate, db: Session = Depends(get_db)):
return crud_highlight.create_highlight(db, highlight)
@router.put("/update_highlight/{highlight_id}", response_model=PatientHighlight, description="Update an existing highlight.")
def update_patient_highlight(highlight_id: int, highlight_data: PatientHighlightUpdate, db: Session = Depends(get_db)):
# Replace with actual user ID in a real-world scenario
modified_by = 1
return update_highlight(db, highlight_id, highlight_data, modified_by)

@router.put("/Highlight/update", response_model=schemas_highlight.Highlight)
def update_highlight(highlight_id: int, highlight: schemas_highlight.HighlightUpdate, db: Session = Depends(get_db)):
db_highlight = crud_highlight.update_highlight(db, highlight_id, highlight)
if not db_highlight:
raise HTTPException(status_code=404, detail="Highlight not found")
return db_highlight

@router.put("/Highlight/delete", response_model=schemas_highlight.Highlight)
def delete_highlight(highlight_id: int, db: Session = Depends(get_db)):
db_highlight = crud_highlight.delete_highlight(db, highlight_id)
if not db_highlight:
raise HTTPException(status_code=404, detail="Highlight not found")
return db_highlight
@router.delete("/delete_highlight/{highlight_id}", response_model=PatientHighlight, description="Soft delete a highlight by ID.")
def delete_patient_highlight(highlight_id: int, db: Session = Depends(get_db)):
# Replace with actual user ID in a real-world scenario
modified_by = 1
return delete_highlight(db, highlight_id, modified_by)
4 changes: 2 additions & 2 deletions app/schemas/patient_assigned_dementia_list.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,5 +24,5 @@ class PatientAssignedDementiaListRead(PatientAssignedDementiaListBase):
CreatedDate: datetime
ModifiedDate: datetime

class Config:
orm_mode = True
model_config = {"from_attributes": True}

2 changes: 1 addition & 1 deletion app/schemas/patient_assigned_dementia_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -41,4 +41,4 @@ class PatientAssignedDementiaCreateResp(BaseModel):
CreatedById: int
ModifiedById: int

model_config = ConfigDict(orm_mode=True)
model_config = {"from_attributes": True}
35 changes: 17 additions & 18 deletions app/schemas/patient_highlight.py
Original file line number Diff line number Diff line change
@@ -1,28 +1,27 @@
from pydantic import BaseModel
from pydantic import BaseModel, Field
from datetime import datetime
from typing import Optional

class PatientHighlightBase(BaseModel):
PatientId: int = Field(..., example=1)
Type: str = Field(..., example="Allergy")
HighlightJSON: str = Field(..., example='{"id":1,"value":"Shellfish"}')
StartDate: datetime = Field(..., example="2024-03-03T00:00:00")
EndDate: datetime = Field(..., example="2024-03-06T00:00:00")
IsDeleted: Optional[str] = Field(default="0", example="0")

class HighlightBase(BaseModel):
patientId: int
description: str
createdDate: datetime
modifiedDate: datetime
createdById: int
modifiedById: int


class HighlightCreate(HighlightBase):
class PatientHighlightCreate(PatientHighlightBase):
pass

class PatientHighlightUpdate(PatientHighlightBase):
pass

class HighlightUpdate(BaseModel):
description: Optional[str] = None
modifiedDate: datetime
modifiedById: int

class PatientHighlight(PatientHighlightBase):
Id: int = Field(..., example=1)
CreatedDate: datetime = Field(..., example="2025-01-04T23:13:59.107")
ModifiedDate: datetime = Field(..., example="2025-01-04T23:13:59.107")
CreatedById: int = Field(..., example=1)
ModifiedById: int = Field(..., example=1)

class Highlight(HighlightBase):
id: int

model_config = {"from_attributes": True}
Original file line number Diff line number Diff line change
Expand Up @@ -32,4 +32,6 @@ ALTER COLUMN [IsDeleted] VARCHAR(1) NOT NULL;

-- Add a default value for IsDeleted as '0'
ALTER TABLE [dbo].[PATIENT_HIGHLIGHT_TYPE]
ADD CONSTRAINT DF_IsDeleted_Default5 DEFAULT ('0') FOR [IsDeleted];
ADD CONSTRAINT DF_IsDeleted_Default5 DEFAULT ('0') FOR [IsDeleted];

ALTER TABLE PATIENT_HIGHLIGHT ALTER COLUMN PatientId INT NOT NULL;
5 changes: 3 additions & 2 deletions tests/test_allergy_reaction_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,8 @@
from app.models.patient_doctor_note_model import PatientDoctorNote
from app.models.patient_photo_model import PatientPhoto
from app.models.patient_model import Patient
from app.models.patient_assigned_dementia_model import PatientAssignedDementia
from app.models.patient_assigned_dementia_list_model import PatientAssignedDementiaList
from app.models.patient_assigned_dementia_mapping_model import PatientAssignedDementiaMapping
from app.models.patient_mobility_model import PatientMobility
from app.models.patient_prescription_model import PatientPrescription
from app.models.patient_social_history_model import PatientSocialHistory
Expand Down Expand Up @@ -50,7 +51,7 @@ def test_get_all_reaction_types(db_session_mock):
"""Test case for getting all allergy reaction types."""

# Arrange
db_session_mock.query.return_value.all.return_value = get_mock_allergy_reaction_types()
db_session_mock.query.return_value.filter.return_value.all.return_value = get_mock_allergy_reaction_types()

# Act
result = get_all_reaction_types(db_session_mock)
Expand Down
6 changes: 3 additions & 3 deletions tests/test_allergy_type.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,8 @@
from app.models.patient_doctor_note_model import PatientDoctorNote
from app.models.patient_photo_model import PatientPhoto
from app.models.patient_model import Patient
from app.models.patient_assigned_dementia_model import PatientAssignedDementia
from app.models.patient_assigned_dementia_list_model import PatientAssignedDementiaList
from app.models.patient_assigned_dementia_mapping_model import PatientAssignedDementiaMapping
from app.models.patient_mobility_model import PatientMobility
from app.models.patient_prescription_model import PatientPrescription
from app.models.patient_social_history_model import PatientSocialHistory
Expand All @@ -30,7 +31,6 @@

# Mocking the relevant models


def test_create_allergy_type(
db_session_mock,
allergy_type_create,
Expand All @@ -54,7 +54,7 @@ def test_create_allergy_type(
def test_get_all_allergy_types(db_session_mock):
"""Test case for retrieving all allergy types."""
# Arrange
db_session_mock.query.return_value.all.return_value = get_mock_allergy_types()
db_session_mock.query.return_value.filter.return_value.all.return_value = get_mock_allergy_types()

# Act
result = get_all_allergy_types(db_session_mock)
Expand Down
3 changes: 2 additions & 1 deletion tests/test_patient_allergy_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@
from app.models.patient_doctor_note_model import PatientDoctorNote
from app.models.patient_photo_model import PatientPhoto
from app.models.patient_model import Patient
from app.models.patient_assigned_dementia_model import PatientAssignedDementia
from app.models.patient_assigned_dementia_list_model import PatientAssignedDementiaList
from app.models.patient_assigned_dementia_mapping_model import PatientAssignedDementiaMapping
from app.models.patient_mobility_model import PatientMobility
from app.models.patient_prescription_model import PatientPrescription
from app.models.patient_social_history_model import PatientSocialHistory
Expand Down
2 changes: 1 addition & 1 deletion tests/test_patient_assigned_dementia_mapping.py
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,6 @@ def get_mock_assigned_dementias():
@mock.patch("app.models.patient_guardian_relationship_mapping_model.PatientGuardianRelationshipMapping")
@mock.patch("app.models.patient_patient_guardian_model.PatientPatientGuardian")
@mock.patch("app.models.allergy_reaction_type_model.AllergyReactionType")
@mock.patch("app.models.patient_assigned_dementia_list_model.PatientAssignedDementiaList")
@mock.patch("app.models.allergy_type_model.AllergyType")
@mock.patch("app.models.patient_social_history_model.PatientSocialHistory")
@mock.patch("app.models.patient_highlight_model.PatientHighlight")
Expand All @@ -76,6 +75,7 @@ def get_mock_assigned_dementias():
@mock.patch("app.models.patient_photo_model.PatientPhoto")
@mock.patch("app.models.patient_doctor_note_model.PatientDoctorNote")
@mock.patch("app.models.patient_allergy_mapping_model.PatientAllergyMapping")
@mock.patch("app.models.patient_assigned_dementia_list_model.PatientAssignedDementiaList")
@mock.patch("app.models.patient_assigned_dementia_mapping_model.PatientAssignedDementiaMapping")
def test_create_assigned_dementia(
mock_patient_assigned_dementia_mapping,
Expand Down
Loading

0 comments on commit e0298fe

Please sign in to comment.