generateur_v3/backend/api/conftest.py

52 lines
1.3 KiB
Python
Raw Normal View History

2022-09-16 21:50:55 +02:00
import os
import shutil
import pytest
from fastapi.testclient import TestClient
from sqlmodel import Session, SQLModel, create_engine, select
from sqlmodel.pool import StaticPool
from database.exercices.models import Exercice
from main import app
from database.db import get_session
2022-10-10 01:34:38 +02:00
import json
import pydantic.json
def _custom_json_serializer(*args, **kwargs) -> str:
"""
Encodes json in the same way that pydantic does.
"""
return json.dumps(*args, default=pydantic.json.pydantic_encoder, **kwargs)
2022-09-16 21:50:55 +02:00
@pytest.fixture(name="session")
def session_fixture():
engine = create_engine(
2022-10-10 01:34:38 +02:00
"sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool, echo=False, json_serializer=_custom_json_serializer
2022-09-16 21:50:55 +02:00
)
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
yield session
#cleanup uploads
exos = session.exec(select(Exercice)).all()
for e in exos:
try:
shutil.rmtree(os.path.join('uploads', e.id_code))
except:
pass
@pytest.fixture(name="client")
def client_fixture(session: Session):
def get_session_override():
return session
app.dependency_overrides[get_session] = get_session_override
client = TestClient(app)
yield client
app.dependency_overrides.clear()