Skip to content

Commit

Permalink
Add get commands test
Browse files Browse the repository at this point in the history
  • Loading branch information
Yarik-Popov committed Nov 4, 2024
1 parent 7ae3aab commit c67647e
Show file tree
Hide file tree
Showing 13 changed files with 124 additions and 67 deletions.
30 changes: 17 additions & 13 deletions backend/api/lifespan.py
Original file line number Diff line number Diff line change
@@ -1,29 +1,33 @@
from contextlib import asynccontextmanager
from datetime import datetime
from fastapi import FastAPI
from sqlmodel import SQLModel, select
from sqlmodel import SQLModel, Session, select
from backend.data.data_models import MainCommand
from backend.data.engine import get_db
from backend.data.mock_data import commands, main_commands
from backend.utils.logging import logger_setup
from backend.utils.time import to_unix_time


@asynccontextmanager
async def lifespan(_: FastAPI):
"""Lifecycle event for the FastAPI app."""
def create_startup(session: Session) -> None:
logger_setup()
SQLModel.metadata.create_all(get_db().connection())
SQLModel.metadata.create_all(session.connection())
default_time = "2024-01-01T00:00:00"
default_datetime = datetime.strptime(default_time, "%Y-%m-%dT%H:%M:%S")
unix_time = to_unix_time(default_datetime)
# Setup the db with mock data
with get_db() as session:
query = select(MainCommand).limit(1) # Check if the db is empty
result = session.exec(query).first()
if result is None:
session.add_all(main_commands())
session.commit()
session.add_all(commands(unix_time))
session.commit()
query = select(MainCommand).limit(1) # Check if the db is empty
result = session.exec(query).first()
if result is None:
session.add_all(main_commands())
session.commit()
session.add_all(commands(unix_time))
session.commit()


@asynccontextmanager
async def lifespan(_: FastAPI):
"""Lifecycle event for the FastAPI app."""
create_startup(get_db())
yield
print("Closing lifespan")
6 changes: 3 additions & 3 deletions backend/api/resources/command.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@


@command_router.get("/", response_model=CommandListResponse)
async def get_commands(db: Session = Depends(get_db)):
def get_commands(db: Session = Depends(get_db)):
"""
Gets all the items
Expand All @@ -22,7 +22,7 @@ async def get_commands(db: Session = Depends(get_db)):


@command_router.post("/", response_model=Command)
async def create_command(payload: CommandRequest):
def create_command(payload: CommandRequest):
"""
Creates an item with the given payload and returns the payload with some other information
Expand All @@ -33,7 +33,7 @@ async def create_command(payload: CommandRequest):


@command_router.delete("/{id}", response_model=CommandListResponse)
async def delete_command(id: int):
def delete_command(id: int):
"""
Deletes the item with the given id if it exists. Otherwise raises a 404 error.
Expand Down
2 changes: 1 addition & 1 deletion backend/api/resources/main_command.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@


@main_command_router.get("/", response_model=MainCommandListResponse)
async def get_main_commands(db: Session = Depends(get_db)):
def get_main_commands(db: Session = Depends(get_db)):
"""
Gets all the main commands that can be created.
Expand Down
4 changes: 2 additions & 2 deletions backend/data/mock_data.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@

def commands(unix_time: int) -> list[Command]:
return [
Command(command_type=1, params=f"{unix_time}"), # id=1, RTC Sync for 2021-01-01
Command(command_type=1, params=f"{unix_time}"), # id=1, RTC Sync for unix time
Command(
command_type=2, params=f"1,{unix_time}"
), # id=2, Emergency mode for 2021-01-01
), # id=2, Emergency mode for unix time
]


Expand Down
Empty file removed backend/domain/__init__.py
Empty file.
4 changes: 0 additions & 4 deletions backend/domain/base_service.py

This file was deleted.

Empty file removed backend/domain/command_service.py
Empty file.
9 changes: 0 additions & 9 deletions backend/domain/iservice.py

This file was deleted.

3 changes: 1 addition & 2 deletions requirements.txt
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,5 @@ sqlmodel==0.0.22
loguru==0.7.2

# Development dependencies
httpx==0.27.2
pytest==7.4.0
pytest==8.3.3
pytest-cov==4.1.0
75 changes: 67 additions & 8 deletions test/backend/conftest.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,29 @@
from contextlib import asynccontextmanager
from datetime import datetime
from sqlmodel import SQLModel, Session, create_engine
from typing import Final
from fastapi import FastAPI
from fastapi.testclient import TestClient
from sqlmodel import SQLModel, Session, create_engine, delete
import pytest
from backend.api.lifespan import create_startup
from backend.api.setup import setup_middlewares, setup_routes
from backend.data.data_models import Command, MainCommand
from backend.data.engine import get_db
from backend.data.mock_data import commands, main_commands
from backend.utils.time import to_unix_time
from json import loads
from sqlmodel.pool import StaticPool

TESTING_SQL_PATH: Final[str] = "sqlite:///testing.db"

def get_mock_db() -> Session:
engine = create_engine(TESTING_SQL_PATH, connect_args={"check_same_thread": False}, poolclass=StaticPool)
with Session(engine) as session:
return session

@pytest.fixture
def db_engine():
sqlite_file_name = "sqlite://" # In memory db for testing
engine = create_engine(sqlite_file_name)
return engine
def mock_db() -> Session:
return get_mock_db()


@pytest.fixture
Expand All @@ -18,11 +32,56 @@ def default_datetime():
return datetime.strptime(default_time, "%Y-%m-%dT%H:%M:%S")


@asynccontextmanager
async def lifespan(_: FastAPI):
db = get_mock_db()
create_startup(db)
yield
del_main_command = delete(MainCommand)
db.exec(del_main_command)
db.commit()
del_command = delete(Command)
db.exec(del_command)
db.commit()


@pytest.fixture
def fastapi_app():
app = FastAPI(lifespan=lifespan)
app.dependency_overrides[get_db] = get_mock_db
setup_routes(app)
setup_middlewares(app)
return app

@pytest.fixture
def fastapi_test_client(fastapi_app):
return TestClient(fastapi_app)

@pytest.fixture
def commands_json(default_datetime):
commands_with_id = []
for i, val in enumerate(commands(to_unix_time(default_datetime)), start=1):
val.id = i
serialize_command = val.model_dump_json()
command = loads(serialize_command)
commands_with_id.append(command)
return commands_with_id


@pytest.fixture(scope="function", autouse=True)
def setup_db(db_engine, default_datetime):
SQLModel.metadata.create_all(db_engine)
with Session(db_engine) as session:
def setup_db(mock_db: Session, default_datetime):
SQLModel.metadata.create_all(mock_db.connection())
with mock_db as session:
session.add_all(main_commands())
session.commit()
session.add_all(commands(to_unix_time(default_datetime)))
session.commit()
yield
del_main_command = delete(MainCommand)
session.exec(del_main_command)
session.commit()
del_command = delete(Command)
session.exec(del_command)
session.commit()


6 changes: 6 additions & 0 deletions test/backend/test_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@

def test_get_commands(fastapi_test_client, commands_json):
with fastapi_test_client as client:
response = client.get("/commands/")
assert response.status_code == 200
assert response.json() == {"data": commands_json}
17 changes: 8 additions & 9 deletions test/backend/test_data.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import pytest
from sqlmodel import Session
from backend.data.data_models import MainCommand


Expand Down Expand Up @@ -31,27 +30,27 @@ def test_main_command_no_params_and_no_format():
assert main_command.total_size == 2


def test_main_command_no_format(db_engine):
with pytest.raises(ValueError), Session(db_engine) as session:
session.add(
def test_main_command_no_format(mock_db):
with pytest.raises(ValueError):
mock_db.add(
MainCommand(
name="Test",
params="param1,param2",
data_size=2,
total_size=2,
)
)
session.commit()
mock_db.commit()


def test_main_command_no_params(db_engine):
with pytest.raises(ValueError), Session(db_engine) as session:
session.add(
def test_main_command_no_params(mock_db):
with pytest.raises(ValueError):
mock_db.add(
MainCommand(
name="Test",
format="int,int",
data_size=2,
total_size=2,
)
)
session.commit()
mock_db.commit()
35 changes: 19 additions & 16 deletions test/backend/test_setup.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
# Test to make sure the conftest.py setup is correct
import pytest
from sqlmodel import Session, select
from backend.data.data_models import MainCommand, Command
from sqlmodel import Session

from backend.utils.time import to_unix_time

Expand All @@ -21,24 +21,27 @@
],
)
def test_main_command_setup(
db_engine, command_id, name, params, format, data_size, total_size
mock_db: Session, command_id, name, params, format, data_size, total_size
):
with Session(db_engine) as session:
main_command = session.get(MainCommand, command_id)
assert main_command
assert main_command.name == name
assert main_command.params == params
assert main_command.format == format
assert main_command.data_size == data_size
assert main_command.total_size == total_size
main_command = mock_db.get(MainCommand, command_id)
assert main_command
assert main_command.name == name
assert main_command.params == params
assert main_command.format == format
assert main_command.data_size == data_size
assert main_command.total_size == total_size
query = select(MainCommand)
all_main_commands = mock_db.exec(query).all()
assert len(all_main_commands) == 2


@pytest.mark.parametrize(
"id, command_type, params", [(1, 1, "{unix_time}"), [2, 2, "1,{unix_time}"]]
)
def test_command_setup(db_engine, id, command_type, params, default_datetime):
with Session(db_engine) as session:
command = session.get(Command, id)
assert command
assert command.command_type == command_type
assert command.params == params.format(unix_time=to_unix_time(default_datetime))
def test_command_setup(mock_db, id, command_type, params, default_datetime):
command = mock_db.get(Command, id)
assert command
assert command.command_type == command_type
assert command.params == params.format(unix_time=to_unix_time(default_datetime))


0 comments on commit c67647e

Please sign in to comment.