I have an error when use db calls in async methods of Django TestCase: "psycopg2.InterfaceError: connection already closed"
I know that I can use TransactionTestCase, but it's slow. Is there solution for this using Django TestCase?
example.py
from django.contrib.auth import get_user_model
from channels.db import database_sync_to_async
async def func():
return await database_sync_to_async(get_user_model().objects.filter(pk=1).exists)()
test_example.py
import django.test
from asgiref.sync import sync_to_async
from .example import func
class TestFunc(django.test.TestCase):
async def test_func(self):
res = await func()
await sync_to_async(self.assertFalse)(res)
I only needed to replace database_sync_to_async
with sync_to_async
:)