Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Creating transactions inside async fixtures with pytest #780

Open
dantownsend opened this issue Mar 1, 2023 · 4 comments
Open

Creating transactions inside async fixtures with pytest #780

dantownsend opened this issue Mar 1, 2023 · 4 comments

Comments

@dantownsend
Copy link
Member

In an ideal world with pytest-asyncio we could do this:

@pytest.fixture(scope="function", autouse=True)
async def piccolo_transaction(event_loop):
    DB: PostgresEngine = engine_finder()
    async with DB.transaction():
        yield

But pytest-asyncio has an issue where contextvars aren't passed from an async fixture, and Piccolo relies on contextvars to track the current transaction.

pytest-dev/pytest-asyncio#127

@dantownsend
Copy link
Member Author

Work around for now:

@pytest.fixture(scope="function", autouse=True)
async def piccolo_transaction(event_loop):
    """
    It should be as simple as::

        async with DB.transaction():
            yield

    However, pytest-asyncio doesn't pass down contextvars, which is how Piccolo
    handles transactions.

    https://github.com/pytest-dev/pytest-asyncio/issues/127

    For now, this is the work around.

    """
    DB: PostgresEngine = engine_finder()

    connection = await DB.get_new_connection()

    transaction = DB.transaction()
    transaction.connection = connection
    transaction.transaction = transaction.connection.transaction()
    await transaction.begin()

    class TransactionProxy:
        def get(self):
            return transaction

    DB.current_transaction = TransactionProxy()

    yield

    await transaction.rollback()
    await connection.close()

@sylvainOL
Copy link

Hello @dantownsend,

do you think this is still relevant as it seems some MR have been merged to fix it (but pytest-dev/pytest-asyncio#127 is still open so I'm not sure :/)

thanks!

@dantownsend
Copy link
Member Author

@sylvainOL This is still the work around I'm using at the moment. I occasionally check in on pytest-asyncio to see if the problem is resolved, but honestly I'm not sure.

It looks like they made some changes in 0.23.0, but I haven't had a chance to check whether this resolves the problem.

@sylvainOL
Copy link

thanks for the quick reply ! I'll continue to use it then.

Thnaks again!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants