2020-04-20 20:31:29 +02:00
|
|
|
from fastapi.testclient import TestClient
|
2024-02-29 15:42:55 -05:00
|
|
|
from sqlmodel import Session
|
2019-02-09 19:42:36 +04:00
|
|
|
|
2019-04-19 09:45:23 +04:00
|
|
|
from app import crud
|
2020-04-16 23:56:10 -06:00
|
|
|
from app.core.config import settings
|
2024-02-29 15:42:55 -05:00
|
|
|
from app.models import User, UserCreate, UserUpdate
|
2020-04-20 20:31:29 +02:00
|
|
|
from app.tests.utils.utils import random_email, random_lower_string
|
2019-02-09 19:42:36 +04:00
|
|
|
|
|
|
|
|
|
2020-04-20 19:03:13 +02:00
|
|
|
def user_authentication_headers(
|
2020-04-20 20:31:29 +02:00
|
|
|
*, client: TestClient, email: str, password: str
|
2024-02-25 19:39:33 +01:00
|
|
|
) -> dict[str, str]:
|
2019-02-09 19:42:36 +04:00
|
|
|
data = {"username": email, "password": password}
|
|
|
|
|
|
2020-04-20 20:31:29 +02:00
|
|
|
r = client.post(f"{settings.API_V1_STR}/login/access-token", data=data)
|
2019-02-09 19:42:36 +04:00
|
|
|
response = r.json()
|
|
|
|
|
auth_token = response["access_token"]
|
|
|
|
|
headers = {"Authorization": f"Bearer {auth_token}"}
|
|
|
|
|
return headers
|
2019-04-19 09:45:23 +04:00
|
|
|
|
|
|
|
|
|
2020-04-20 19:03:13 +02:00
|
|
|
def create_random_user(db: Session) -> User:
|
2020-04-06 11:36:29 +02:00
|
|
|
email = random_email()
|
2019-04-19 09:45:23 +04:00
|
|
|
password = random_lower_string()
|
2024-02-29 15:42:55 -05:00
|
|
|
user_in = UserCreate(email=email, password=password)
|
|
|
|
|
user = crud.create_user(session=db, user_create=user_in)
|
2019-04-19 09:45:23 +04:00
|
|
|
return user
|
2020-01-19 13:25:17 +01:00
|
|
|
|
|
|
|
|
|
2020-04-20 20:31:29 +02:00
|
|
|
def authentication_token_from_email(
|
|
|
|
|
*, client: TestClient, email: str, db: Session
|
2024-02-25 19:39:33 +01:00
|
|
|
) -> dict[str, str]:
|
2020-01-19 13:25:17 +01:00
|
|
|
"""
|
|
|
|
|
Return a valid token for the user with given email.
|
|
|
|
|
|
|
|
|
|
If the user doesn't exist it is created first.
|
|
|
|
|
"""
|
|
|
|
|
password = random_lower_string()
|
2024-02-29 15:42:55 -05:00
|
|
|
user = crud.get_user_by_email(session=db, email=email)
|
2020-01-19 13:25:17 +01:00
|
|
|
if not user:
|
2024-02-29 15:42:55 -05:00
|
|
|
user_in_create = UserCreate(email=email, password=password)
|
|
|
|
|
user = crud.create_user(session=db, user_create=user_in_create)
|
2020-01-19 13:25:17 +01:00
|
|
|
else:
|
2020-04-20 19:03:13 +02:00
|
|
|
user_in_update = UserUpdate(password=password)
|
2024-03-10 14:47:21 -05:00
|
|
|
if not user.id:
|
|
|
|
|
raise Exception("User id not set")
|
2024-02-29 15:42:55 -05:00
|
|
|
user = crud.update_user(session=db, user_id=user.id, user_in=user_in_update)
|
2020-01-19 13:25:17 +01:00
|
|
|
|
2020-04-20 20:31:29 +02:00
|
|
|
return user_authentication_headers(client=client, email=email, password=password)
|