Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
async def test_json_websocket_consumer():
"""
Tests that JsonWebsocketConsumer is implemented correctly.
"""
results = {}
class TestConsumer(JsonWebsocketConsumer):
def connect(self):
self.accept()
def receive_json(self, data=None):
results["received"] = data
self.send_json(data)
# Open a connection
communicator = WebsocketCommunicator(TestConsumer, "/testws/")
connected, _ = await communicator.connect()
assert connected
# Test sending
await communicator.send_json_to({"hello": "world"})
response = await communicator.receive_json_from()
assert response == {"hello": "world"}
assert results["received"] == {"hello": "world"}
# Test sending bytes breaks it
await communicator.send_to(bytes_data=b"w\0\0\0")
with pytest.raises(ValueError):
await communicator.wait()
# Statistics
if job_object.stop_time is not None:
result['stop_time'] = timezone.localtime(job_object.stop_time).strftime('%d-%b-%Y, %H:%M:%S')
else:
result['stop_time'] = None
if job_object.time_taken is not None:
result['time_taken'] = job_object.get_time_taken()
else:
result['time_taken'] = None
result['status'] = str(job_object.status)
return result
if created:
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
"job_details" + "-" + instance.uuid,
{
"type": "message",
"message": data()
}
)
if instance:
channel_layer = get_channel_layer()
async_to_sync(channel_layer.group_send)(
"job_details" + "-" + instance.uuid,
{
"type": "message",
"message": data()
}
shipment, _ = await sync_to_async(Shipment.objects.get_or_create)(
id=random_id(),
owner_id=USER_ID,
storage_credentials_id=random_id(),
shipper_wallet_id=random_id(),
carrier_wallet_id=random_id(),
contract_version='1.0.0'
)
# Update shipment (should get a message)
shipment.carriers_scac = 'TESTING123'
await sync_to_async(shipment.save)()
# Have to manually send message to channel
channel_layer = get_channel_layer()
await channel_layer.group_send(shipment.owner_id, {
"type": "shipments.update",
"shipment_id": shipment.id
})
# Re-enable Shipment post-save signal
await sync_to_async(models.signals.post_save.connect)(shipment_post_save, sender=Shipment,
dispatch_uid='shipment_post_save')
response = await communicator.receive_json_from()
assert response['event'] == EventTypes.shipment_update.name
assert response['data']['data']['type'] == 'Shipment'
assert response['data']['data']['attributes']['carriers_scac'] == shipment.carriers_scac
await communicator.disconnect()
)
response = await communicator.receive_json_from()
assert response == {
"action": "retrieve",
"errors": ["Not found"],
"response_status": 404,
"request_id": 1,
"data": None
}
u1 = await database_sync_to_async(get_user_model().objects.create)(
username='test1', email='42@example.com'
)
u2 = await database_sync_to_async(get_user_model().objects.create)(
username='test2', email='45@example.com'
)
# lookup a pk that is not there
await communicator.send_json_to(
{
"action": "retrieve",
"pk": u1.id - 1,
"request_id": 1
}
)
response = await communicator.receive_json_from()
assert response == {
"action": "retrieve",
self.send(text_data="Hello world!")
if django.VERSION >= (2, 0):
from django.urls import path
router = URLRouter(
[
path("basic-http/", BasicHttpConsumer),
path("basic-ws/", BasicWebsocketConsumer),
path("", AsgiHandler),
]
)
else:
from django.conf.urls import url
router = URLRouter(
[
url(r"^basic-http/$", BasicHttpConsumer),
url(r"^basic-ws/$", BasicWebsocketConsumer),
url(r"^$", AsgiHandler),
]
)
return AuthMiddlewareStack(router)
def test_path_remaining():
"""
Resolving continues in outer router if an inner router has no matching
routes
"""
inner_router = URLRouter([url(r"^no-match/$", MagicMock(return_value=1))])
test_app = MagicMock(return_value=2)
outer_router = URLRouter(
[url(r"^prefix/", inner_router), url(r"^prefix/stuff/$", test_app)]
)
outermost_router = URLRouter([url(r"", outer_router)])
assert outermost_router({"type": "http", "path": "/prefix/stuff/"}) == 2
with path().
"""
from django.urls import path
test_app = MagicMock(return_value=1)
inner_router = URLRouter([path("test//", test_app)])
def asgi_middleware(inner):
# Some middleware which hides the fact that we have an inner URLRouter
def app(scope):
return inner(scope)
app._path_routing = True
return app
outer_router = URLRouter(
[path("number//", asgi_middleware(inner_router))]
)
assert inner_router({"type": "http", "path": "/test/3/"}) == 1
assert outer_router({"type": "http", "path": "/number/42/test/3/"}) == 1
assert test_app.call_args[0][0]["url_route"] == {
"args": (),
"kwargs": {"number": 42, "page": 3},
}
with pytest.raises(ValueError):
assert outer_router({"type": "http", "path": "/number/42/test/3/bla/"})
with pytest.raises(ValueError):
assert outer_router({"type": "http", "path": "/number/42/blub/"})
def test_normal_run(self):
consumer = mock.Mock()
Channel('test').send({'test': 'test'}, immediately=True)
channel_layer = channel_layers[DEFAULT_CHANNEL_LAYER]
channel_layer.router.add_route(route('test', consumer))
old_send = channel_layer.send
channel_layer.send = mock.Mock(side_effect=old_send) # proxy 'send' for counting
worker = PatchedWorker(channel_layer)
worker.termed = 2
worker.run()
self.assertEqual(consumer.call_count, 1)
self.assertEqual(channel_layer.send.call_count, 0)
# -*- coding: utf-8 -*-
from __future__ import absolute_import, print_function, unicode_literals
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from django.urls import path
from knocker.routing import channel_routing as knocker_routing
application = ProtocolTypeRouter({
'websocket': AuthMiddlewareStack(
URLRouter([
path('knocker/', knocker_routing),
])
def callback(attr: str, old: Any, new: Any) -> None:
if new == 1:
data['y'] = [0, 10, 20, 30, 40, 50]
else:
data['y'] = [i * new for i in [0, 10, 20, 30, 40, 50]]
source.data = ColumnDataSource(data=data).data
plot.y_range.end = max(data['y'])
slider = Slider(start=1, end=5, value=1, step=1, title="Test App Bokeh + Channels Controller")
slider.on_change("value", callback)
doc.add_root(column(slider, plot))
class TestWS(WebsocketConsumer):
def connect(self):
self.accept()
def receive(self, text_data):
text_data_json = json.loads(text_data)
message = text_data_json['client_message']
self.send(text_data=json.dumps({
'server_message': message
}))
def disconnect(self, close_code):
pass