当前位置: 首页>>代码示例>>Python>>正文


Python testing.WebsocketCommunicator方法代码示例

本文整理汇总了Python中channels.testing.WebsocketCommunicator方法的典型用法代码示例。如果您正苦于以下问题:Python testing.WebsocketCommunicator方法的具体用法?Python testing.WebsocketCommunicator怎么用?Python testing.WebsocketCommunicator使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在channels.testing的用法示例。


在下文中一共展示了testing.WebsocketCommunicator方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: test_ping_consumer

# 需要导入模块: from channels import testing [as 别名]
# 或者: from channels.testing import WebsocketCommunicator [as 别名]
def test_ping_consumer(self):
        communicator = WebsocketCommunicator(PingConsumer, '/tracker/ws/ping/')
        connected, subprotocol = await communicator.connect()
        self.assertTrue(connected, 'Could not connect')
        await communicator.send_to(text_data='PING')
        result = await communicator.receive_from()
        # TODO: python 3.7 has datetime.datetime.fromisoformat
        date = dateutil.parser.parse(result)
        now = datetime.datetime.now(pytz.utc)
        self.assertTrue(
            (date - now).total_seconds() < 5,
            msg=f'{date} and {now} differed by more than five seconds',
        )
        await communicator.disconnect() 
开发者ID:GamesDoneQuick,项目名称:donation-tracker,代码行数:16,代码来源:test_consumers.py

示例2: __aenter__

# 需要导入模块: from channels import testing [as 别名]
# 或者: from channels.testing import WebsocketCommunicator [as 别名]
def __aenter__(self):
        self.communicator = WebsocketCommunicator(WebsocketConsumer, '/')
        return self.communicator 
开发者ID:yunity,项目名称:karrot-backend,代码行数:5,代码来源:test_consumers.py

示例3: test_can_connect_with_file_origin

# 需要导入模块: from channels import testing [as 别名]
# 或者: from channels.testing import WebsocketCommunicator [as 别名]
def test_can_connect_with_file_origin(self):
        application = AllowedHostsAndFileOriginValidator(WebsocketConsumer)
        communicator = WebsocketCommunicator(application, '/', headers=[(b'origin', b'file:///')])
        connected, _ = await communicator.connect()
        assert connected
        await communicator.disconnect() 
开发者ID:yunity,项目名称:karrot-backend,代码行数:8,代码来源:test_consumers.py

示例4: test_observer_wrapper

# 需要导入模块: from channels import testing [as 别名]
# 或者: from channels.testing import WebsocketCommunicator [as 别名]
def test_observer_wrapper(settings):
    settings.CHANNEL_LAYERS = {
        "default": {
            "BACKEND": "channels.layers.InMemoryChannelLayer",
            "TEST_CONFIG": {"expiry": 100500,},
        },
    }

    layer = channel_layers.make_test_backend(DEFAULT_CHANNEL_LAYER)

    class TestConsumer(AsyncAPIConsumer):
        async def accept(self):
            await self.handle_user_logged_in.subscribe()
            await super().accept()

        @observer(user_logged_in)
        async def handle_user_logged_in(self, *args, observer=None, **kwargs):
            await self.send_json({"message": kwargs, "observer": observer is not None})

    communicator = WebsocketCommunicator(TestConsumer, "/testws/")

    connected, _ = await communicator.connect()

    assert connected

    user = await database_sync_to_async(get_user_model().objects.create)(
        username="test", email="test@example.com"
    )

    await database_sync_to_async(user_logged_in.send)(
        sender=user.__class__, request=None, user=user
    )

    response = await communicator.receive_json_from()

    assert {"message": {}, "observer": True} == response

    await communicator.disconnect() 
开发者ID:hishnash,项目名称:djangochannelsrestframework,代码行数:40,代码来源:test_observer.py

示例5: test_model_observer_wrapper

# 需要导入模块: from channels import testing [as 别名]
# 或者: from channels.testing import WebsocketCommunicator [as 别名]
def test_model_observer_wrapper(settings):
    settings.CHANNEL_LAYERS = {
        "default": {
            "BACKEND": "channels.layers.InMemoryChannelLayer",
            "TEST_CONFIG": {"expiry": 100500,},
        },
    }

    layer = channel_layers.make_test_backend(DEFAULT_CHANNEL_LAYER)

    class TestConsumer(AsyncAPIConsumer):
        async def accept(self):
            await TestConsumer.user_change.subscribe(self)
            await super().accept()

        @model_observer(get_user_model())
        async def user_change(self, message, observer=None, **kwargs):
            await self.send_json(message)

    communicator = WebsocketCommunicator(TestConsumer, "/testws/")

    connected, _ = await communicator.connect()

    assert connected

    user = await database_sync_to_async(get_user_model().objects.create)(
        username="test", email="test@example.com"
    )

    response = await communicator.receive_json_from()

    assert {"action": "create", "pk": user.pk, "type": "user.change"} == response

    await communicator.disconnect() 
开发者ID:hishnash,项目名称:djangochannelsrestframework,代码行数:36,代码来源:test_observer.py

示例6: test_model_observer_delete_wrapper

# 需要导入模块: from channels import testing [as 别名]
# 或者: from channels.testing import WebsocketCommunicator [as 别名]
def test_model_observer_delete_wrapper(settings):
    settings.CHANNEL_LAYERS = {
        "default": {
            "BACKEND": "channels.layers.InMemoryChannelLayer",
            "TEST_CONFIG": {"expiry": 100500,},
        },
    }

    layer = channel_layers.make_test_backend(DEFAULT_CHANNEL_LAYER)

    class TestConsumer(AsyncAPIConsumer):
        async def accept(self):
            await TestConsumer.user_change.subscribe(self)
            await super().accept()

        @model_observer(get_user_model())
        async def user_change(self, message, observer=None, **kwargs):
            await self.send_json(message)

    communicator = WebsocketCommunicator(TestConsumer, "/testws/")

    connected, _ = await communicator.connect()

    assert connected
    user = await database_sync_to_async(get_user_model())(
        username="test", email="test@example.com"
    )
    await database_sync_to_async(user.save)()

    response = await communicator.receive_json_from()

    assert {"action": "create", "pk": user.pk, "type": "user.change"} == response
    pk = user.pk

    await database_sync_to_async(user.delete)()

    response = await communicator.receive_json_from()

    assert {"action": "delete", "pk": pk, "type": "user.change"} == response

    await communicator.disconnect() 
开发者ID:hishnash,项目名称:djangochannelsrestframework,代码行数:43,代码来源:test_observer.py

示例7: test_view_as_consumer

# 需要导入模块: from channels import testing [as 别名]
# 或者: from channels.testing import WebsocketCommunicator [as 别名]
def test_view_as_consumer():

    results = {}

    class TestView(APIView):
        def get(self, request, format=None):
            results["TestView-get"] = True
            return Response(["test1", "test2"])

    # Test a normal connection
    communicator = WebsocketCommunicator(
        view_as_consumer(TestView.as_view()), "/testws/"
    )

    connected, _ = await communicator.connect()
    assert connected

    await communicator.send_json_to({"action": "retrieve", "request_id": 1})

    response = await communicator.receive_json_from()

    assert "TestView-get" in results

    assert response == {
        "errors": [],
        "data": ["test1", "test2"],
        "action": "retrieve",
        "response_status": 200,
        "request_id": 1,
    } 
开发者ID:hishnash,项目名称:djangochannelsrestframework,代码行数:32,代码来源:test_django_view_consumer.py

示例8: test_consumer_connect

# 需要导入模块: from channels import testing [as 别名]
# 或者: from channels.testing import WebsocketCommunicator [as 别名]
def test_consumer_connect():
    communicator = WebsocketCommunicator(application, "/knocker/notification/en/")
    connected, __ = await communicator.connect()
    assert connected
    assert await communicator.receive_nothing() is True
    await communicator.disconnect() 
开发者ID:nephila,项目名称:django-knocker,代码行数:8,代码来源:test_consumers.py

示例9: test_consumer_notification

# 需要导入模块: from channels import testing [as 别名]
# 或者: from channels.testing import WebsocketCommunicator [as 别名]
def test_consumer_notification():
    @database_sync_to_async
    def get_post(title):
        return Post.objects.create(
            title=title,
            slug=slugify(title),
        )

    @database_sync_to_async
    def get_noknock_post(title):
        return NoKnockPost.objects.create(
            title=title,
            slug=slugify(title),
        )

    communicator = WebsocketCommunicator(application, "/knocker/notification/en/")
    await communicator.connect()

    # Post type which return notifications
    post = await get_post('first post')
    notification = json.loads(await communicator.receive_json_from())
    assert notification['title'] == 'new {0}'.format(post._meta.verbose_name)
    assert notification['message'] == post.title
    assert notification['url'] == post.get_absolute_url()

    # Post type without notifications
    await get_noknock_post('first post')
    assert await communicator.receive_nothing() is True
    await communicator.disconnect() 
开发者ID:nephila,项目名称:django-knocker,代码行数:31,代码来源:test_consumers.py

示例10: test_single_tenant_chat_consumer

# 需要导入模块: from channels import testing [as 别名]
# 或者: from channels.testing import WebsocketCommunicator [as 别名]
def test_single_tenant_chat_consumer():
    settings.CHANNEL_LAYERS = TEST_CHANNEL_LAYERS
    client, room, user = prepare_room_and_user()
    communicator = WebsocketCommunicator(
        application, f"/ws/django_chatter/chatrooms/{room.id}/",
        headers=[
            (
                b'cookie',
                f'sessionid={client.cookies["sessionid"].value}'.encode('ascii')
            ),
            (b'host', b'localhost:8000')]
        )
    connected, subprotocol = await communicator.connect()
    assert connected
    data = {
        'message_type': 'text',
        'message': "Hello!",
        'sender': user.username,
        'room_id': str(room.id),
        }
    await communicator.send_json_to(data)
    response = await communicator.receive_json_from()
    assert response['message'] == "Hello!"
    assert response['sender'] == "user0"
    assert response['room_id'] == str(room.id)
    await communicator.disconnect() 
开发者ID:dibs-devs,项目名称:chatter,代码行数:28,代码来源:test_consumers.py

示例11: test_multitenant_chat_consumer

# 需要导入模块: from channels import testing [as 别名]
# 或者: from channels.testing import WebsocketCommunicator [as 别名]
def test_multitenant_chat_consumer():
    settings.CHANNEL_LAYERS = TEST_CHANNEL_LAYERS
    client, room, user = prepare_room_and_user()
    communicator = WebsocketCommunicator(
        multitenant_application, f"/ws/django_chatter/chatrooms/{room.id}/",
        headers=[
            (
                b'cookie',
                f'sessionid={client.cookies["sessionid"].value}'.encode('ascii')
            ),
            (b'host', b'localhost:8000')]
        )
    connected, subprotocol = await communicator.connect()
    assert connected
    data = {
        'message_type': 'text',
        'message': "Hello!",
        'sender': user.username,
        'room_id': str(room.id),
        }
    await communicator.send_json_to(data)
    response = await communicator.receive_json_from()
    response = response
    message = Message.objects.all()[0]
    time = message.date_created
    # zone = pytz.timezone(get_default_timezone_name())
    # time = time.astimezone(tz=zone)
    # formatted = dateformat.DateFormat(time)
    # time = formatted.format('M d, Y h:i a')

    assert response['message_type'] == 'text'
    assert response['message'] == 'Hello!'
    assert response['sender'] == 'user0'
    assert response['room_id'] == str(room.id)
    assert response['date_created'] == time.strftime("%d %b %Y %H:%M:%S %Z")
    await communicator.disconnect() 
开发者ID:dibs-devs,项目名称:chatter,代码行数:38,代码来源:test_consumers.py

示例12: test_harmful_message_in_chat_consumer

# 需要导入模块: from channels import testing [as 别名]
# 或者: from channels.testing import WebsocketCommunicator [as 别名]
def test_harmful_message_in_chat_consumer():
    settings.CHANNEL_LAYERS = TEST_CHANNEL_LAYERS
    client, room, user = prepare_room_and_user()
    communicator = WebsocketCommunicator(
        application, f"/ws/django_chatter/chatrooms/{room.id}/",
        headers=[
            (
                b'cookie',
                f'sessionid={client.cookies["sessionid"].value}'.encode('ascii')
            ),
            (b'host', b'localhost:8000')]
        )
    connected, subprotocol = await communicator.connect()
    assert connected
    data = {
        'message_type': 'text',
        'message': "<script>evil();</script>",
        'sender': user.username,
        'room_id': str(room.id),
        }
    await communicator.send_json_to(data)
    response = await communicator.receive_json_from()
    assert response['message'] == "&lt;script&gt;evil();&lt;/script&gt;"
    assert response['sender'] == "user0"
    assert response['room_id'] == str(room.id)
    await communicator.disconnect() 
开发者ID:dibs-devs,项目名称:chatter,代码行数:28,代码来源:test_consumers.py

示例13: test_no_host_in_headers

# 需要导入模块: from channels import testing [as 别名]
# 或者: from channels.testing import WebsocketCommunicator [as 别名]
def test_no_host_in_headers():
    settings.CHANNEL_LAYERS = TEST_CHANNEL_LAYERS
    room = Room.objects.create()
    user = get_user_model().objects.create(username="user0")
    room.members.add(user)
    room.save()
    client = Client()
    client.force_login(user=user)
    with pytest.raises(ValueError):
        communicator = WebsocketCommunicator(
            multitenant_application, f"/ws/django_chatter/chatrooms/{room.id}/",
            ) 
开发者ID:dibs-devs,项目名称:chatter,代码行数:14,代码来源:test_utils.py

示例14: _get_communicator

# 需要导入模块: from channels import testing [as 别名]
# 或者: from channels.testing import WebsocketCommunicator [as 别名]
def _get_communicator(self, request_vars, user=None):
        communicator = WebsocketCommunicator(LocationBroadcast, request_vars['path'])
        if user:
            communicator.scope.update(
                {
                    'user': user,
                    'session': request_vars['session'],
                    'url_route': {'kwargs': {'pk': request_vars['pk']}},
                }
            )
        return communicator 
开发者ID:openwisp,项目名称:openwisp-controller,代码行数:13,代码来源:pytest.py

示例15: _get_communicator

# 需要导入模块: from channels import testing [as 别名]
# 或者: from channels.testing import WebsocketCommunicator [as 别名]
def _get_communicator(self, request_vars, user=None):
        communicator = WebsocketCommunicator(LocationBroadcast, request_vars['path'])
        if user:
            communicator.scope.update(
                {
                    "user": user,
                    "session": request_vars['session'],
                    "url_route": {"kwargs": {"pk": request_vars['pk']}},
                }
            )
        return communicator 
开发者ID:openwisp,项目名称:django-loci,代码行数:13,代码来源:test_channels.py


注:本文中的channels.testing.WebsocketCommunicator方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。