2020-04-20 19:03:13 +02:00
|
|
|
from typing import Dict
|
|
|
|
|
|
2020-04-20 20:31:29 +02:00
|
|
|
from fastapi.testclient import TestClient
|
2020-04-20 19:03:13 +02:00
|
|
|
from sqlalchemy.orm 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
|
2023-11-25 00:08:22 +01:00
|
|
|
from app.models import User
|
2020-01-19 22:40:50 +01:00
|
|
|
from app.schemas.user import 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
|
2020-04-20 19:03:13 +02: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()
|
|
|
|
|
user_in = UserCreate(username=email, email=email, password=password)
|
2020-04-20 19:03:13 +02:00
|
|
|
user = crud.user.create(db=db, obj_in=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
|
|
|
|
|
) -> 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()
|
2020-04-20 19:03:13 +02:00
|
|
|
user = crud.user.get_by_email(db, email=email)
|
2020-01-19 13:25:17 +01:00
|
|
|
if not user:
|
2020-04-20 19:03:13 +02:00
|
|
|
user_in_create = UserCreate(username=email, email=email, password=password)
|
|
|
|
|
user = crud.user.create(db, obj_in=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)
|
|
|
|
|
user = crud.user.update(db, db_obj=user, obj_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)
|