Skip to content

added AsyncSingleThreadContext #511

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

Open
wants to merge 1 commit into
base: main
Choose a base branch
from

Conversation

Arfey
Copy link

@Arfey Arfey commented Apr 26, 2025

I have a problem with async database connections for Django TestCase.

The psycopg3 connection is not thread-safe. As a result, I need to create a new connection per thread. This is a problem for the TestCase coz it uses a transaction for each test case.

class TestCase(TransactionTestCase):
    async def _apost_teardown(self):
        for conn in async_connections.all(initialized_only=True):
            await conn.close()

    def _setup_and_call(self, result, debug=False):
        if iscoroutinefunction(testMethod):
            ############### convert test 
            setattr(self, self._testMethodName, async_to_sync(testMethod))

        if debug:
            super().debug()
        else:
            super().__call__(result)

       self._post_teardown()
       ############### convert teardown 
       async_to_sync(self._apost_teardown)()       

I can do something like that coz each async_to_sync function uses a new thread executor (and different connection as a result). To solve that, I try to implement something similar for ThreadSensitiveContext.

class TestCase(TransactionTestCase):
    def _setup_and_call(self, result, debug=False):
        with AsyncSingleThreadContext()
            if iscoroutinefunction(testMethod):
                ############### convert test 
                setattr(self, self._testMethodName, async_to_sync(testMethod))

            if debug:
                super().debug()
            else:
                super().__call__(result)

           self._post_teardown()
           ############### convert teardown 
           async_to_sync(self._apost_teardown)()       

@Arfey Arfey force-pushed the feat/added-async-single-thread-context branch from ebccae6 to 495ec35 Compare May 2, 2025 23:09
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

Successfully merging this pull request may close these issues.

1 participant