tests.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. from asgiref.sync import async_to_sync
  2. from django.core.exceptions import SynchronousOnlyOperation
  3. from django.test import SimpleTestCase
  4. from django.utils.asyncio import async_unsafe
  5. from .models import SimpleModel
  6. class DatabaseConnectionTest(SimpleTestCase):
  7. """A database connection cannot be used in an async context."""
  8. @async_to_sync
  9. async def test_get_async_connection(self):
  10. with self.assertRaises(SynchronousOnlyOperation):
  11. list(SimpleModel.objects.all())
  12. class AsyncUnsafeTest(SimpleTestCase):
  13. """
  14. async_unsafe decorator should work correctly and returns the correct
  15. message.
  16. """
  17. @async_unsafe
  18. def dangerous_method(self):
  19. return True
  20. @async_to_sync
  21. async def test_async_unsafe(self):
  22. # async_unsafe decorator catches bad access and returns the right
  23. # message.
  24. msg = (
  25. 'You cannot call this from an async context - use a thread or '
  26. 'sync_to_async.'
  27. )
  28. with self.assertRaisesMessage(SynchronousOnlyOperation, msg):
  29. self.dangerous_method()