【问题标题】:Is this possible: Django TestCase + async + db calls?这可能吗:Django TestCase + async + db 调用?
【发布时间】: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


    【解决方案1】:

    我只需要将database_sync_to_async 替换为sync_to_async :)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多