Pytest test failing when run with other tests but passes when run by itself

Question:

I very basic test that checks if a user that is not logged in can connect to my websocket that is as follows:

@pytest.mark.asyncio
async def test_unauthenticated_cant_connect_to_websocket(unauthenticated_websocket_communicator: WebsocketCommunicator):
    connected, subprotocol = await unauthenticated_websocket_communicator.connect()
    assert subprotocol == 3000  # subprotocol 3000 is Unauthorised
    assert connected is False

This test passes when i test it by itself from the cli using pytest -k test_unauthenticated_cant_connect_to_websocket

but fails when i use pytest from the cli

my consumer connect function is as follows:

async def websocket_connect(self, event: dict) -> None:
    if self.scope["user"].is_anonymous:
        await self.close(code=3000)
    else:
        await self.accept()

I have a number of other async tests with similar types of code but they all pass.

Asked By: liam

||

Answers:

I fixed the issue by adding a @pytest.mark.django_db decorator to the test.

Answered By: liam
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.