3

我在异步代码中使用 Django ORM。一切正常,所有测试都通过。但是,数据库连接在测试后没有正确关闭。这是一个例子:

from asgiref.sync import sync_to_async, async_to_sync


@sync_to_async
def count_books():
    return Book.objects.count()


class FooTest(TestCase):
    def setUp(self):
        Book.objects.create(title='Haha')

    def test1(self):
        import asyncio
        c = asyncio.run(count_books())
        self.assertEqual(1, c)

    def test2(self):
        c = async_to_sync(count_books)()
        self.assertEqual(1, c)

Postgres 错误:

django.db.utils.OperationalError: database "test_mydbname" is being accessed by other users

Sqlite 错误:

sqlite3.OperationalError: database table is locked: test_mydbname

我试过从 django-channels 交换sync_to_asyncdatabase_sync_to_async但这并没有改变任何东西。

我怎样才能解决这个问题?

4

1 回答 1

2

问题在于你的异步运行循环如何与主线程交互,你自己处理这个可能会变得相当复杂。

对于测试django-channels,我建议使用pytestwithpytest-asyncio测试通道。当然pytest-django

这将为测试异步代码提供一些有用的工具。

@pytest.mark.django_db(transaction=True)
@pytest.mark.asyncio
async def test1():
    count = await database_sync_to_async(Book.objects.count)
    ....

有关如何测试通道代码的一些示例,请查看此处

于 2020-02-15T19:50:02.447 回答