compass/backend/test/services/user_test_data.py

115 lines
2.9 KiB
Python

import pytest
from sqlalchemy.orm import Session
from ...models.user_model import User
# import model enums instead
from ...models.enum_for_models import UserTypeEnum, ProgramTypeEnum
from ...entities.user_entity import UserEntity
from datetime import datetime
programs = ProgramTypeEnum
roles = UserTypeEnum
volunteer = User(
id=1,
username="volunteer",
email="volunteer@compass.com",
experience=1,
group="volunteers",
programtype=[programs.COMMUNITY.value],
created_at=datetime.now(),
usertype=UserTypeEnum.VOLUNTEER.value
)
employee = User(
id=2,
username="employee",
email="employee@compass.com",
experience=5,
group="employees",
programtype=[programs.DOMESTIC.value, programs.ECONOMIC.value],
created_at=datetime.now(),
usertype=roles.EMPLOYEE.value,
)
admin = User(
id=3,
username="admin",
email="admin@compass.com",
experience=10,
group="admin",
programtype=[programs.ECONOMIC.value, programs.DOMESTIC.value, programs.COMMUNITY.value],
created_at=datetime.now(),
usertype=roles.ADMIN.value,
)
newUser = User(
id=4,
username="new",
email="new@compass.com",
experience=1,
group="volunteer",
programtype=[programs.ECONOMIC.value],
created_at=datetime.now(),
usertype=roles.VOLUNTEER.value
)
users = [volunteer, employee, admin]
from sqlalchemy import text
from sqlalchemy.orm import Session, DeclarativeBase, InstrumentedAttribute
def reset_table_id_seq(
session: Session,
entity: type[DeclarativeBase],
entity_id_column: InstrumentedAttribute[int],
next_id: int,
) -> None:
"""Reset the ID sequence of an entity table.
Args:
session (Session) - A SQLAlchemy Session
entity (DeclarativeBase) - The SQLAlchemy Entity table to target
entity_id_column (MappedColumn) - The ID column (should be an int column)
next_id (int) - Where the next inserted, autogenerated ID should begin
Returns:
None"""
table = entity.__table__
id_column_name = entity_id_column.name
sql = text(f"ALTER SEQUENCe {table}_{id_column_name}_seq RESTART WITH {next_id}")
session.execute(sql)
def insert_fake_data(session: Session):
"""Inserts fake organization data into the test session."""
global users
# Create entities for test organization data
entities = []
for user in users:
entity = UserEntity.from_model(user)
session.add(entity)
entities.append(entity)
# Reset table IDs to prevent ID conflicts
reset_table_id_seq(session, UserEntity, UserEntity.id, len(users) + 1)
# Commit all changes
session.commit()
@pytest.fixture(autouse=True)
def fake_data_fixture(session: Session):
"""Insert fake data the session automatically when test is run.
Note:
This function runs automatically due to the fixture property `autouse=True`.
"""
insert_fake_data(session)
session.commit()
yield