本文整理匯總了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()
示例2: __aenter__
# 需要導入模塊: from channels import testing [as 別名]
# 或者: from channels.testing import WebsocketCommunicator [as 別名]
def __aenter__(self):
self.communicator = WebsocketCommunicator(WebsocketConsumer, '/')
return self.communicator
示例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()
示例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()
示例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()
示例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()
示例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,
}
示例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()
示例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()
示例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()
示例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()
示例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'] == "<script>evil();</script>"
assert response['sender'] == "user0"
assert response['room_id'] == str(room.id)
await communicator.disconnect()
示例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}/",
)
示例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
示例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