How do we properly mock async_engine and async_sessionmaker in python?

169 views Asked by At

I'm using SQLAlchemy and a Postgres DB in a project and wanted to write unit tests for a function which writes to the database. I'd like to use mocks instead of actually writing to a test database and I'm using the following code to create the clients in the actual code.

async_engine = create_async_engine(
    "postgresql+asyncpg://",
    isolation_level="REPEATABLE READ",
)


async_ses = async_sessionmaker(
    autocommit=False, autoflush=False, bind=async_engine
)


async def write_to_db():
    async with async_ses() as db:
        obj = (
                (await db.execute(select(Item).where(Item.id == 100)))
                .scalars()
                .first()
            )
         ...

I then use the following pytest fixtures to mock this:

@pytest.fixture
async def mock_async_engine():
    # Mock the async engine
    mock_engine = MagicMock()  # Create a mock or MagicMock for AsyncEngine
    with patch('db.async_engine', return_value=mock_engine):
        yield mock_engine

@pytest.fixture
async def mock_async_session():
    # Mock the async session
    mock_session = MagicMock()  # Create a mock or MagicMock for AsyncSession
    with patch('db.async_ses', return_value=mock_session):
        yield mock_session


@pytest.mark.asyncio
async def test_write_to_db(mock_async_engine, mock_async_session):
    async with async_ses() as db:
        # TEST

However I noticed that it ends up writing to the actual database instead of mocking it out.

0

There are 0 answers