system-pri/backend/tests/utils.py

98 lines
2.8 KiB
Python
Raw Normal View History

import datetime
from typing import List, Type, Union
from factory.alchemy import SQLAlchemyModelFactory
from flask.testing import FlaskClient
from app.dependencies import db
from app.students.models import Group
def assert_model_changes(model: db.Model, expected_data: dict) -> None:
for key, val in expected_data.items():
value = getattr(model, key)
if isinstance(value, datetime.datetime):
value = value.strftime("%Y-%m-%dT%H:%M:%S.000Z")
assert value == val
def _test_case_client_without_response(
test_client: FlaskClient,
url: str,
data: Union[dict, None],
status_code: int,
method: str = "post",
) -> dict:
method_func = getattr(test_client, method)
if data is not None:
response = method_func(url, json=data)
else:
response = method_func(url)
# raise Exception(response.status_code, response.json)
assert response.status_code == status_code
return response.json
def _test_case_client(
test_client: FlaskClient,
url: str,
data: Union[dict, None],
message: str,
status_code: int,
key: str = "message",
method: str = "post",
) -> dict:
response_data = _test_case_client_without_response(
test_client, url, data, status_code, method
)
assert key in response_data.keys()
assert response_data.get(key) == message
return response_data
def _test_case_group(group: Group, data: dict) -> None:
assert group.name == data["name"]
assert group.project_supervisor_id == data["project_supervisor_id"]
for st in group.students:
assert st.id in data["students"]
def create_many_models(
amount: int, factory: Type[SQLAlchemyModelFactory], **kwargs
) -> List[SQLAlchemyModelFactory]:
models = [factory(**kwargs) for _ in range(amount)]
db.session.add_all(models)
db.session.commit()
return models
def create_one_model(
model: Union[Type[db.Model], Type[SQLAlchemyModelFactory]],
data: dict = None,
**kwargs
) -> Union[db.Model, SQLAlchemyModelFactory]:
if issubclass(model, SQLAlchemyModelFactory):
m = model(**kwargs) # it's a factory
else:
m = model(**data, **kwargs)
db.session.add(m)
db.session.commit()
return m
def get_data_of_term_of_defence(timedelta_minutes: int = 30) -> dict:
ex = ExaminationSchedule.query.first()
if ex is None:
date = datetime.datetime.now()
else:
date = ex.start_date
return {
"start_date": (date + datetime.timedelta(days=1)).strftime(
"%Y-%m-%dT%H:%M:%S.000Z"
),
"end_date": (
date + datetime.timedelta(days=1, minutes=timedelta_minutes)
).strftime("%Y-%m-%dT%H:%M:%S.000Z"),
}