我在Django TestCase: "psycopg2的异步方法中使用db调用时出现错误。InterfaceError:连接已关闭">
我知道我可以使用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)
我只需要将database_sync_to_async
替换为sync_to_async
:)