Skip to content

Commit

Permalink
feat: add fixtures for tests
Browse files Browse the repository at this point in the history
  • Loading branch information
raf-nr committed Dec 15, 2023
1 parent 45c68da commit 2edb4f5
Show file tree
Hide file tree
Showing 3 changed files with 452 additions and 0 deletions.
54 changes: 54 additions & 0 deletions tests/conftest.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import pytest
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from app.db.base_model import Base
from app.settings import get_settings

settings = get_settings()

tables = [
"Code",
"User",
"Role",
"Permission",
"Feedback",
"Device",
"Session",
"ColumnStats",
"FileFormat",
"FileInfo",
"Task",
]

test_engine = create_engine(settings.postgres_test_dsn.unicode_string())


@pytest.fixture(scope="session", autouse=True)
def session_test():
Session = sessionmaker(test_engine, expire_on_commit=False)
yield Session


@pytest.fixture(scope="session", autouse=True)
def create_tables():
Base.metadata.create_all(test_engine)


@pytest.fixture(scope="session", autouse=True)
def drop_tables_at_end(session_test):
yield
Base.metadata.drop_all(test_engine)


@pytest.fixture(scope="function", autouse=True)
def clean_tables(request, session_test):
if "fixture_name" in request.fixturenames:
yield
else:
with session_test() as session:
with session.connection():
for table_name in tables:
table = Base.metadata.tables[table_name]
session.query(table).delete()
session.commit()
yield
35 changes: 35 additions & 0 deletions tests/fixtures/fetch_data_from_db.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import pytest
from app.db import tables


@pytest.fixture(scope="function")
def fetch_all_data_from_table(session_test):
def fetch_all_data(model_name: str):
with session_test() as session:
with session.connection():
data = session.query(tables[model_name]).all()
return data

return fetch_all_data


@pytest.fixture(scope="function")
def fetch_data_by_id_from_table(session_test):
def fetch_data_by_id(model_name: str, id: str | int):
with session_test() as session:
with session.connection():
data = session.get(tables[model_name], id)
return data

return fetch_data_by_id


@pytest.fixture(scope="function")
def fetch_first_from_table(session_test):
def fetch_first(model_name: str):
with session_test() as session:
with session.connection():
data = session.query(tables[model_name]).first()
return data

return fetch_first
Loading

0 comments on commit 2edb4f5

Please sign in to comment.