Django通道Postgres接口错误:连接已关闭
我似乎不能在这件事上聚精会神。我正在为我的渠道消费者编写测试。我通常会使用Django默认的unittest,但由于通道需要使用pytest,所以我会使用它,但仍然希望维护编写测试的类结构 我在编写类似于unittest的设置方法时遇到了问题,我将使用unittest初始化测试属性。我尝试使用类fixture,但它们似乎都不起作用,因为我无法访问测试方法中的实例属性。最后,我决定编写Django通道Postgres接口错误:连接已关闭,django,postgresql,pytest,python-asyncio,django-channels,Django,Postgresql,Pytest,Python Asyncio,Django Channels,我似乎不能在这件事上聚精会神。我正在为我的渠道消费者编写测试。我通常会使用Django默认的unittest,但由于通道需要使用pytest,所以我会使用它,但仍然希望维护编写测试的类结构 我在编写类似于unittest的设置方法时遇到了问题,我将使用unittest初始化测试属性。我尝试使用类fixture,但它们似乎都不起作用,因为我无法访问测试方法中的实例属性。最后,我决定编写setup实例方法,并为每个类手动调用它。这就是我到目前为止所做的: @pytest.mark.django_db
setup
实例方法,并为每个类手动调用它。这就是我到目前为止所做的:
@pytest.mark.django_db
@pytest.mark.asyncio
class TestChatConsumer(object):
@database_sync_to_async
def set_up(self):
self.user = UserFactory()
self.api_client = APIClientFactory()
self.token = TokenFactory(user=self.user)
self.credentials = {
'AUTHORIZATION': self.token.key,
...
}
self.credentials_params = '&'.join(['{}={}'.format(k, v) for k, v in self.credentials.items()])
self.authless_endpoint = '/api/v1/ws/'
self.endpoint = self.authless_endpoint + '?' + self.credentials_params
async def test_connect_without_credentials(self):
await self.set_up()
communicator = WebsocketCommunicator(application, self.authless_endpoint)
connected, subprotocol = await communicator.connect()
assert not connected
async def test_connect_with_credentials(self):
await self.set_up()
communicator = WebsocketCommunicator(application, self.endpoint)
connected, subprotocol = await communicator.connect()
assert connected
问题是,当我的消费者试图在connect
方法中访问数据库的代码时,我不断得到psycopg2.interface错误:连接已经关闭。它使用database\u sync\u to\u async
,在我手动测试它时工作得非常好
具体而言,connect
方法中引发错误的行如下所示:
await database_sync_to_async(user.inbox.increment_connections)().
不确定到底是什么问题,因为数据库\u sync\u to \u async
应该正确清理旧连接,以便正确创建新连接
非常感谢您的帮助。显然我找错地方了。问题是这样的:
等待数据库同步到异步(user.inbox.increment\u connections)(
)
收件箱
是一个相关的管理器,因此它尝试在实际的数据库\u sync\u to \u async
之前获取它,但由于需要db调用,因此失败
我尝试了这个wait database\u sync\u to\u async(user).inbox.increment\u connections()
,但它不起作用,因为它包装了一个方法,而不是一个属性,所以我最后做的是在身份验证期间使用prefetch\u related
来获取inbox
。这样一来,user.inbox
就不再需要数据库调用,而且工作正常