-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathdb_connection.py
More file actions
56 lines (44 loc) · 1.5 KB
/
db_connection.py
File metadata and controls
56 lines (44 loc) · 1.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
from pytest import fixture # noqa PT013
from pytest_asyncio import fixture as async_fixture
from sqlalchemy.engine import make_url
from sqlalchemy.ext.asyncio import AsyncSession, create_async_engine
from sqlalchemy.orm import sessionmaker
from tests.common import sqla_uri
from tests.models import Base
def get_async_sessionmaker() -> sessionmaker:
engine = create_async_engine(url=make_url(sqla_uri()))
_async_session = sessionmaker(bind=engine, class_=AsyncSession, expire_on_commit=False)
return _async_session
async def async_session_dependency():
"""
Get session as dependency
:return:
"""
session_maker = get_async_sessionmaker()
async with session_maker() as db_session: # type: AsyncSession
yield db_session
await db_session.rollback()
@async_fixture(scope="class")
async def async_engine():
engine = create_async_engine(
url=make_url(sqla_uri()),
# TODO: env var
echo=False,
# echo=True,
)
async with engine.begin() as conn:
await conn.run_sync(Base.metadata.drop_all)
await conn.run_sync(Base.metadata.create_all)
return engine
@async_fixture(scope="class")
async def async_session_plain(async_engine):
session = sessionmaker(
bind=async_engine,
class_=AsyncSession,
expire_on_commit=False,
)
return session
@async_fixture(scope="class")
async def async_session(async_session_plain):
async with async_session_plain() as session:
yield session