Add unit tests

This commit is contained in:
linuskmr 2021-12-23 17:58:44 +01:00
parent 23aa9a905b
commit 4d5875a3aa

View file

@ -0,0 +1,113 @@
from datetime import datetime, timedelta
import pytest
from fastapi.testclient import TestClient
from fastapi import status
from sqlmodel import create_engine, Session, SQLModel, select
from sqlmodel.pool import StaticPool
from src import database
from src.main import app
from src.models.project import Project
@pytest.fixture(name="session")
def session_fixture():
"""Creates a mock session, that access an in-memory temporary database."""
engine = create_engine(
"sqlite://", # In memory database
connect_args={"check_same_thread": False}, # FastAPI's async functions may execute on different threads
poolclass=StaticPool # All threads should access shared memory
)
SQLModel.metadata.create_all(engine)
with Session(engine) as session:
yield session
@pytest.fixture(name="client")
def client_fixture(session: Session):
"""Creates a FastAPI TestClient with a mocked session dependency. This causes FastAPI to inject the fake session
into path operation functions, so that we have full control over the mocked database."""
def get_session_override():
return session
app.dependency_overrides[database.get_session] = get_session_override
client = TestClient(app)
yield client
app.dependency_overrides.clear()
def test_project_create(client: TestClient):
project = {"name": "Uni"}
response = client.post("/projects/", json=project)
response_data: dict = response.json()
assert response.status_code == status.HTTP_201_CREATED
assert project.items() <= response_data.items() # Is subset, i.e. was all send data saved?
assert response_data["id"] # Not empty?
assert response_data["creation_date"] # Not empty?
def test_project_get(client: TestClient, session: Session):
# Fill database
project = Project(name="Uni", creation_date=datetime.now())
session.add(project)
session.commit()
# Request data from API
response = client.get("/projects/Uni")
response_data = response.json()
assert response.status_code == status.HTTP_200_OK
assert response_data["id"] # Not empty?
assert response_data["name"] == project.name
assert response_data["creation_date"] == project.creation_date.isoformat()
def test_project_update(client: TestClient, session: Session):
# Fill database
project = Project(name="Uni", creation_date=datetime.now())
session.add(project)
session.commit()
# Perform update via API
project_updates = {"name": "UNI"}
response = client.patch("/projects/Uni", json=project_updates)
response_data = response.json()
assert response.status_code == status.HTTP_200_OK
assert response_data["id"] # Not empty?
assert response_data["name"] == project_updates["name"]
assert response_data["creation_date"] == project.creation_date.isoformat()
def test_project_delete(client: TestClient, session: Session):
# Fill database
project = Project(name="Uni", creation_date=datetime.now())
session.add(project)
session.commit()
# Delete via API
response = client.delete("/projects/Uni")
response_data = response.json()
assert response.status_code == status.HTTP_204_NO_CONTENT
assert session.exec(select(Project).where(Project.name == "Uni")).first() is None # Element deleted from database?
def test_project_get_list(client: TestClient, session: Session):
pass
# Fill database
project_uni = Project(name="Uni", creation_date=datetime.now())
project_sport = Project(name="Sport", creation_date=datetime.now())
session.add(project_uni)
session.add(project_sport)
session.commit()
# Request data from API
response = client.get("/projects/")
response_data = response.json()
assert response.status_code == status.HTTP_200_OK
assert len(response_data) == 2
assert response_data[0]["name"] == project_uni.name
assert response_data[0]["id"] # Not empty?
assert response_data[0]["creation_date"] == project_uni.creation_date.isoformat()
assert response_data[1]["name"] == project_sport.name
assert response_data[1]["id"] # Not empty?
assert response_data[1]["creation_date"] == project_sport.creation_date.isoformat()