Skip to content

Commit

Permalink
- candidate search fix
Browse files Browse the repository at this point in the history
- improved candidate search test
  • Loading branch information
onstabb committed Dec 6, 2023
1 parent 3276d2a commit d3ceca0
Show file tree
Hide file tree
Showing 10 changed files with 22 additions and 22 deletions.
2 changes: 1 addition & 1 deletion src/candidates/service.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def get_candidates_for_user(user: User, limit: int = 1) -> list[dict]:
},

{"$lookup":
{"from": "user_contact",
{"from": "contact",
"let": {"user_id": "$_id"},
"pipeline": [
{"$match":
Expand Down
3 changes: 1 addition & 2 deletions src/contacts/routers.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,14 +29,13 @@ def get_contact(current_user: CurrentActiveCompletedUser, target_user: TargetAct

@router.post("", response_model=ContactOut, status_code=status.HTTP_201_CREATED)
def create_contact(data_in: ContactCreateDataIn, current_user: CurrentActiveCompletedUser):

if data_in.user_id == current_user.id:
raise HTTPException(
status_code=status.HTTP_403_FORBIDDEN, detail="You cannot create contact with yourself",
)

target_user = get_active_completed_user(data_in.user_id)
contact: Contact | None = service.get_contact_by_users_pair(current_user.id, target_user.id)
contact: Contact | None = service.get_contact_by_users_pair(current_user, target_user)

if contact:
raise HTTPException(
Expand Down
7 changes: 6 additions & 1 deletion src/location/database.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,12 @@ def __init__(self) -> None:
def connect(self, data_source: Path | str = config.DB_GEONAMES_DATA_SOURCE) -> None:

self.__conn = connect(data_source, check_same_thread=False)
self.__conn.create_function("DISTANCE", 4, helpers.calculate_distance_, deterministic=True)
self.__conn.create_function(
name="DISTANCE",
narg=4,
func=lambda long1, lat1, long2, lat2: helpers.calculate_distance((long1, lat1), (long2, lat2)),
deterministic=True
)
self.__conn.row_factory = _convert_row
self.__cursor = self.__conn.cursor()
log.info('Connected source "%s""', data_source)
Expand Down
5 changes: 0 additions & 5 deletions src/location/helpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,8 +12,3 @@ def calculate_distance(first_point: GeoPoint, second_point: GeoPoint) -> float:
:return: float distance in km
"""
return vincenty(first_point, second_point, miles=False)



def calculate_distance_(longitude_1: float, latitude_1: float, longitude_2: float, latitude_2: float) -> float:
return calculate_distance((longitude_1, latitude_1), (longitude_2, latitude_2))
2 changes: 1 addition & 1 deletion src/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ async def lifespan(_app_instance: FastAPI):
geonames_db.close()


app = FastAPI(title="I'm not alone")
app = FastAPI(title="I'm not alone", lifespan=lifespan)
app.include_router(api_router)
app.mount('/static', StaticFiles(directory=config.STATIC_PATH, check_dir=True), name="static")
admin.mount_to(app)
3 changes: 0 additions & 3 deletions src/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@ class PydanticObjectId(ObjectId):

@classmethod
def validate(cls, value: typing.AnyStr | ObjectId | LazyReference) -> typing.Self:

if isinstance(value, bytes):
value = value.decode("utf-8")

Expand All @@ -33,7 +32,6 @@ def validate(cls, value: typing.AnyStr | ObjectId | LazyReference) -> typing.Sel
def __get_pydantic_core_schema__(
cls, _source: typing.Any, _handler: GetCoreSchemaHandler
) -> core_schema.CoreSchema:

schema = core_schema.chain_schema(
[
core_schema.union_schema(
Expand All @@ -46,7 +44,6 @@ def __get_pydantic_core_schema__(
core_schema.no_info_plain_validator_function(cls.validate)
]
)

return core_schema.json_or_python_schema(
serialization=core_schema.plain_serializer_function_ser_schema(lambda instance: str(instance)),
python_schema=schema,
Expand Down
10 changes: 6 additions & 4 deletions src/userprofile/birthdate.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
__all__ = ('BirthDate', 'Age')

from datetime import date, datetime
from datetime import date, datetime, timedelta
from typing import Annotated

from pydantic import PastDate, AfterValidator, BeforeValidator, PositiveInt
Expand All @@ -16,10 +16,12 @@ def validate_birthdate(value: date) -> date:
return value


def validate_age(value: int | date) -> int:
def validate_age(value: int | date | datetime) -> int:
if isinstance(value, date) or isinstance(value, datetime):
delta = date.today() - date(value.year, value.month, value.day)
return delta.days
birthdate = date(value.year, value.month, value.day)
age = (date.today() - birthdate) // timedelta(days=365.2425)
return age

return value


Expand Down
5 changes: 3 additions & 2 deletions src/users/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,13 +23,13 @@ def get_current_user_by_token(subject: str = Depends(JWTBearer), ) -> User:

def get_current_active_user(user: User = Depends(get_current_user_by_token)) -> User:
if not user.is_active:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Activation is required")
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Activation is required")
return user


def get_current_active_completed_user(user: User = Depends(get_current_active_user)) -> User:
if not user.profile or not user.photo_urls:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Completed userprofile is required")
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail="Completed profile is required")
return user


Expand All @@ -43,6 +43,7 @@ def get_active_completed_user(user_id: PydanticObjectId) -> User:
return user


CurrentUser = Annotated[User, Depends(get_current_user_by_token)]
CurrentActiveUser = Annotated[User, Depends(get_current_active_user)]
CurrentActiveCompletedUser = Annotated[User, Depends(get_current_active_completed_user)]
TargetActiveCompletedUser = Annotated[User, Depends(get_active_completed_user)]
2 changes: 1 addition & 1 deletion tests/test_authorization/test_api.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ def test_confirm_sms(client, user_factory):
assert new_password


def test_incorrect_login(client, user_factory):
def test_login_incorrect(client, user_factory):
user = user_factory.build(password="incorrect")

response = client.post(
Expand Down
5 changes: 3 additions & 2 deletions tests/test_candidates/test_service.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,9 +5,10 @@
from users.schemas import UserPublicOut


def test_get_candidates_for_user(user_factory):
def test_get_candidates_for_user(user_factory, contact_factory):
user_factory.create_batch(size=5)
user = user_factory.create(profile__gender_preference=None)
existed_contact = contact_factory.create(initiator=user, respondent__profile__gender_preference=None)

result = service.get_candidates_for_user(user, limit=5)

Expand All @@ -16,7 +17,7 @@ def test_get_candidates_for_user(user_factory):

for candidate in map(UserPublicOut.model_validate, result):
candidate: UserPublicOut
assert candidate.id != existed_contact.respondent.id
assert user.profile.gender == candidate.profile.gender_preference or not candidate.profile.gender_preference
assert user.profile.gender_preference == candidate.profile.gender or not user.profile.gender_preference
assert user.role not in UserRole.managers()

0 comments on commit d3ceca0

Please sign in to comment.