#32409: TestCase async tests are not transaction-aware
-------------------------------------+-------------------------------------
Reporter: David | Owner: nobody
Type: New feature | Status: new
Component: Testing framework | Version: 3.1
Severity: Normal | Resolution:
Keywords: TestCase, async, | Triage Stage: Accepted
transaction |
Has patch: 0 | Needs documentation: 0
Needs tests: 0 | Patch needs improvement: 0
Easy pickings: 0 | UI/UX: 0
-------------------------------------+-------------------------------------
Comment (by David):
Hi Carlton,
I did not think about nested `sync_to_async` and `async_to_sync` could
cause issue.
My use case is the following: I have a websocket users use to acquire and
release "lock" on a specific database row, the "lock" is also a database
table which connects user and the other one. Database access is required
by websocket since it needs to verify that the requested element was not
already locked by an other user (and this is the failing test).
My backend was build with Django v2.2 and Channels v1 (using also
multiplexing).
I am now moving to Django v3 which has forced me also to update Channels
since otherwise there would be a conflict with `asgiref` dependency.
Since from Channels v1 to v2 (also v3) there are many breaking changes I
have been forced to rewrite my unittests. Reading
[https://docs.djangoproject.com/en/3.1/topics/testing/tools/#async-tests
Django 3.1 supporting async testing] I thought to try it out (since I am
not familiar with pytest fixtures and database presets) and migrate my
existing tests.
I had a similar issue with an other websocket, which was due to
authorization (since I use a permission-check mechanism to accept
websocket connections), which was work-arounded by pre-fetching
permissions and test user in `TestCase`:
{{{
#!python
class ConsumerTestCase(TestCase):
fixtures = ['test_authorization', ]
@classmethod
def setUpTestData(cls):
user = User.objects.get_by_natural_key('other')
assign_perm('app.model', user) # from guardian.shortcuts import
assign_perm
# force perm cache to be evaluated here
# without this even if DB is in sync there could be a miss-read
due to transactions
user.has_perm('app.model')
cls.user = user
async def test_connect(self):
application = AuthMiddlewareStack(WebsocketConsumer.as_asgi())
communicator = self._connect_to_consumer(application)
connected, _subprotocol = await communicator.connect()
self.assertTrue(connected)
}}}
--
Ticket URL: <https://code.djangoproject.com/ticket/32409#comment:4>
Django <https://code.djangoproject.com/>
The Web framework for perfectionists with deadlines.
--
You received this message because you are subscribed to the Google Groups
"Django updates" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
To view this discussion on the web visit
https://groups.google.com/d/msgid/django-updates/064.f42b8b76705e739616cf80aa538d86f2%40djangoproject.com.