← full-stack-fastapi-template / backend/tests/utils/user.py
| 1 | from fastapi.testclient import TestClient |
| 2 | from sqlmodel import Session |
| 3 | |
| 4 | from app import crud |
| 5 | from app.core.config import settings |
| 6 | from app.models import User, UserCreate, UserUpdate |
| 7 | from tests.utils.utils import random_email, random_lower_string |
| 8 | |
| 9 | |
| 10 | def user_authentication_headers( |
| 11 | *, client: TestClient, email: str, password: str |
| 12 | ) -> dict[str, str]: |
| 13 | data = {"username": email, "password": password} |
| 14 | |
| 15 | r = client.post(f"{settings.API_V1_STR}/login/access-token", data=data) |
| 16 | response = r.json() |
| 17 | auth_token = response["access_token"] |
| 18 | headers = {"Authorization": f"Bearer {auth_token}"} |
| 19 | return headers |
| 20 | |
| 21 | |
| 22 | def create_random_user(db: Session) -> User: |
| 23 | email = random_email() |
| 24 | password = random_lower_string() |
| 25 | user_in = UserCreate(email=email, password=password) |
| 26 | user = crud.create_user(session=db, user_create=user_in) |
| 27 | return user |
| 28 | |
| 29 | |
| 30 | def authentication_token_from_email( |
| 31 | *, client: TestClient, email: str, db: Session |
| 32 | ) -> dict[str, str]: |
| 33 | """ |
| 34 | Return a valid token for the user with given email. |
| 35 | |
| 36 | If the user doesn't exist it is created first. |
| 37 | """ |
| 38 | password = random_lower_string() |
| 39 | user = crud.get_user_by_email(session=db, email=email) |
| 40 | if not user: |
| 41 | user_in_create = UserCreate(email=email, password=password) |
| 42 | user = crud.create_user(session=db, user_create=user_in_create) |
| 43 | else: |
| 44 | user_in_update = UserUpdate(password=password) |
| 45 | if not user.id: |
| 46 | raise Exception("User id not set") |
| 47 | user = crud.update_user(session=db, db_user=user, user_in=user_in_update) |
| 48 | |
| 49 | return user_authentication_headers(client=client, email=email, password=password) |
| 50 |