Skip to content

Problem with UUID inside url route in async testing #1802

@Massakera

Description

@Massakera

I've built a simple chatroom and now I want to code a test to verify if Its connecting. Following the tutorial in Channels docs i come up with the following test:

class ViewTestCase(TestCase):
@classmethod
def setUp(self):
    user_moderator = User.objects.create_superuser(first_name='tester',
        username='test1', 
        password='123', 
        email='testuser@gmail.com')

    user_player = User.objects.create_user(first_name='player',
    username='player1',
    password='1234',
    email='testplayer@gmail.com')

    pack1 = Pack.objects.create(deckStyle='Fibonacci',deck=['1','2','3'])

    self.room = PokerRoom.objects.create(status='Pending',name='planning',styleCards='Fibonacci',
    user=User.objects.get(username='test1'),
    deck=Pack.objects.get(deckStyle='Fibonacci'),index=1)
    
    user_player = ParticipatingUser.objects.create(name='player',idRoom=PokerRoom.objects.get(name='planning'), status='Pending')

    self.story = Story.objects.create(storyName='testplanning',
    idRoom=PokerRoom.objects.get(name='planning'),
    status='Pending')



    
async def test_consumer(self):
    
    application = URLRouter([
        url(r'ws/chat/(?P<room_name>[A-Za-z0-9_-]+)/participant/(?P<user>\w+)/$', consumers.ChatConsumer.as_asgi()),
    ])
    communicator = WebsocketCommunicator(application,"/ws/chat/room_id/participant/participant_id)/")
    connected, subprotocol = await communicator.connect()
    assert connected    
    await communicator.disconnect()

My problem is that I need to substitute room_id and participant_id inside my WebsocketCommunicator. participant_id is just an commom id and my room_id is a UUIDField. I've been using the following method to extract these ids in my others tests:

      def test_something(self):
        room_id = PokerRoom.objects.get(name='planning').id
        user_id = User.objects.get(username='tester').id
        ...

But if I use the same method inside async def like this:

async def test_something(self):
        room_id = PokerRoom.objects.get(name='planning').id
        user_id = User.objects.get(username='tester').id
        ...

I get this error django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async.

How can I solve this?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions