【发布时间】:2021-10-03 06:30:12
【问题描述】:
在 Django TestCase 的异步方法中使用 db 调用时出现错误:“psycopg2.InterfaceError: connection already closed”
我知道我可以使用 TransactionTestCase,但它很慢。 有没有使用 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)
【问题讨论】:
标签: django database asynchronous testcase