def test_websockets_consumers_handlers(self): class WebsocketConsumer(websockets.WebsocketConsumer): def connect(self, message, **kwargs): self.called = 'connect' self.id = kwargs['id'] def disconnect(self, message, **kwargs): self.called = 'disconnect' def receive(self, text=None, bytes=None, **kwargs): self.text = text with apply_routes( [route_class(WebsocketConsumer, path='/path/(?P<id>\d+)')]): client = Client() consumer = client.send_and_consume('websocket.connect', {'path': '/path/1'}) self.assertEqual(consumer.called, 'connect') self.assertEqual(consumer.id, '1') consumer = client.send_and_consume('websocket.receive', { 'path': '/path/1', 'text': 'text' }) self.assertEqual(consumer.text, 'text') consumer = client.send_and_consume('websocket.disconnect', {'path': '/path/1'}) self.assertEqual(consumer.called, 'disconnect')
class TestStreamConsumerReceive(ChannelTestCase): @classmethod def setUpTestData(cls): super(TestStreamConsumerReceive, cls).setUpTestData() cls.content = ContentFactory() def setUp(self): super(TestStreamConsumerReceive, self).setUp() self.client = Client() def test_receive_sends_reply_content(self): self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/public/", "text": '{"action": "load_content", "ids": [%s]}' % self.content.id, }, ) receive = self.client.receive() text = json.loads(receive["text"]) self.assertEqual(text["event"], "content") self.assertEqual(text["contents"], [{ "id": self.content.id, "author": self.content.author.id, "rendered": self.content.rendered, }])
def test_websockets_consumers_handlers(self): class WebsocketConsumer(websockets.WebsocketConsumer): def connect(self, message, **kwargs): self.called = 'connect' self.id = kwargs['id'] def disconnect(self, message, **kwargs): self.called = 'disconnect' def receive(self, text=None, bytes=None, **kwargs): self.text = text with apply_routes([route_class(WebsocketConsumer, path='/path/(?P<id>\d+)')]): client = Client() consumer = client.send_and_consume('websocket.connect', {'path': '/path/1'}) self.assertEqual(consumer.called, 'connect') self.assertEqual(consumer.id, '1') consumer = client.send_and_consume('websocket.receive', {'path': '/path/1', 'text': 'text'}) self.assertEqual(consumer.text, 'text') consumer = client.send_and_consume('websocket.disconnect', {'path': '/path/1'}) self.assertEqual(consumer.called, 'disconnect')
def test_base_consumer(self): class Consumers(BaseConsumer): method_mapping = { 'test.create': 'create', 'test.test': 'test', } def create(self, message, **kwargs): self.called = 'create' def test(self, message, **kwargs): self.called = 'test' with apply_routes([route_class(Consumers)]): client = Client() # check that methods for certain channels routes successfully self.assertEqual( client.send_and_consume('test.create').called, 'create') self.assertEqual( client.send_and_consume('test.test').called, 'test') # send to the channels without routes client.send('test.wrong') message = self.get_next_message('test.wrong') self.assertEqual(client.channel_layer.router.match(message), None) client.send('test') message = self.get_next_message('test') self.assertEqual(client.channel_layer.router.match(message), None)
def test_as_route_method(self): class WebsocketConsumer(BaseConsumer): trigger = 'new' def test(self, message, **kwargs): self.message.reply_channel.send({'trigger': self.trigger}) method_mapping = {'mychannel': 'test'} with apply_routes([WebsocketConsumer.as_route( {'method_mapping': method_mapping, 'trigger': 'from_as_route'}, name='filter')]): client = Client() client.send_and_consume('mychannel', {'name': 'filter'}) self.assertEqual(client.receive(), {'trigger': 'from_as_route'})
def test_consumer(self): client = Client() with apply_routes([MyConsumer.as_route()]): spy.reset_mock() client.send_and_consume(u'websocket.connect', {'path': '/'}) client.send_and_consume( u'websocket.receive', { 'path': '/', 'text': json.dumps({ 'type': 'INCREMENT_COUNTER', 'payload': 2, }), }) self.assertEqual(spy.call_count, 1) self.assertEqual( client.receive(), { 'text': json.dumps({ 'type': 'INCREMENTED_COUNTER', 'payload': 2, }), })
def test_base_consumer(self): class Consumers(BaseConsumer): method_mapping = { 'test.create': 'create', 'test.test': 'test', } def create(self, message, **kwargs): self.called = 'create' def test(self, message, **kwargs): self.called = 'test' with apply_routes([route_class(Consumers)]): client = Client() # check that methods for certain channels routes successfully self.assertEqual(client.send_and_consume('test.create').called, 'create') self.assertEqual(client.send_and_consume('test.test').called, 'test') # send to the channels without routes client.send('test.wrong') message = self.get_next_message('test.wrong') self.assertEqual(client.channel_layer.router.match(message), None) client.send('test') message = self.get_next_message('test') self.assertEqual(client.channel_layer.router.match(message), None)
def test_as_route_method(self): class WebsocketConsumer(BaseConsumer): trigger = 'new' def test(self, message, **kwargs): self.message.reply_channel.send({'trigger': self.trigger}) method_mapping = {'mychannel': 'test'} with apply_routes([ WebsocketConsumer.as_route( { 'method_mapping': method_mapping, 'trigger': 'from_as_route' }, name='filter') ]): client = Client() client.send_and_consume('mychannel', {'name': 'filter'}) self.assertEqual(client.receive(), {'trigger': 'from_as_route'})
def test_websocket_demultiplexer_send(self): class MyWebsocketConsumer(websockets.JsonWebsocketConsumer): def receive(self, content, multiplexer=None, **kwargs): import pdb pdb.set_trace() # breakpoint 69f2473b // self.send(content) class Demultiplexer(websockets.WebsocketDemultiplexer): consumers = {"mystream": MyWebsocketConsumer} with apply_routes([ route_class(Demultiplexer, path='/path/(?P<id>\d+)'), route_class(MyWebsocketConsumer), ]): client = Client() with self.assertRaises(SendNotAvailableOnDemultiplexer): client.send_and_consume( 'websocket.receive', { 'path': '/path/1', 'text': json.dumps({ "stream": "mystream", "payload": { "text_field": "mytext" } }) }) client.receive()
def test_websockets_decorators(self): class WebsocketConsumer(websockets.WebsocketConsumer): slight_ordering = True def connect(self, message, **kwargs): self.order = message['order'] with apply_routes([route_class(WebsocketConsumer, path='/path')]): client = Client() client.send('websocket.connect', {'path': '/path', 'order': 1}) client.send('websocket.connect', {'path': '/path', 'order': 0}) client.consume('websocket.connect') self.assertEqual(client.consume('websocket.connect').order, 0) self.assertEqual(client.consume('websocket.connect').order, 1)
def test_websockets_decorators(self): class WebsocketConsumer(websockets.WebsocketConsumer): strict_ordering = True def connect(self, message, **kwargs): self.order = message['order'] with apply_routes([route_class(WebsocketConsumer, path='/path')]): client = Client() client.send('websocket.connect', {'path': '/path', 'order': 1}) client.send('websocket.connect', {'path': '/path', 'order': 0}) client.consume('websocket.connect') self.assertEqual(client.consume('websocket.connect').order, 0) self.assertEqual(client.consume('websocket.connect').order, 1)
def setUp(self): super(ResourceBindingTestCase, self).setUp() self.client = Client()
class ResourceBindingTestCase(ChannelTestCase): def setUp(self): super(ResourceBindingTestCase, self).setUp() self.client = Client() def _send_and_consume(self, channel, data): """Helper that sends and consumes message and returns the next message.""" self.client.send_and_consume(force_text(channel), data) return self._get_next_message() def _get_next_message(self): msg = self.client.get_next_message(self.client.reply_channel) return json.loads(msg['text']) def _build_message(self, stream, payload): return { "text": json.dumps({ "stream": stream, "payload": payload }), "path": "/" } def test_create(self): """Integration that asserts routing a message to the create channel. Asserts response is correct and an object is created. """ json_content = self._send_and_consume( "websocket.receive", self._build_message( "testmodel", { 'action': 'create', 'pk': None, 'request_id': 'client-request-id', 'data': { 'name': 'some-thing' } })) # it should create an object self.assertEqual(TestModel.objects.count(), 1) expected = { 'action': 'create', 'data': TestModelSerializer(TestModel.objects.first()).data, 'errors': [], 'request_id': 'client-request-id', 'response_status': 201 } # it should respond with the serializer.data self.assertEqual(json_content['payload'], expected) def test_create_failure(self): """Integration that asserts error handling of a message to the create channel.""" json_content = self._send_and_consume( 'websocket.receive', self._build_message( "testmodel", { 'action': 'create', 'pk': None, 'request_id': 'client-request-id', 'data': {}, })) # it should not create an object self.assertEqual(TestModel.objects.count(), 0) expected = { 'action': 'create', 'data': None, 'request_id': 'client-request-id', 'errors': [{ 'name': ['This field is required.'] }], 'response_status': 400 } # it should respond with an error self.assertEqual(json_content['payload'], expected) def test_delete(self): instance = TestModel.objects.create(name='test-name') json_content = self._send_and_consume( 'websocket.receive', self._build_message( 'testmodel', { 'action': 'delete', 'pk': instance.id, 'request_id': 'client-request-id', })) expected = { 'action': 'delete', 'errors': [], 'data': {}, 'request_id': 'client-request-id', 'response_status': 200 } self.assertEqual(json_content['payload'], expected) self.assertEqual(TestModel.objects.count(), 0) def test_delete_failure(self): json_content = self._send_and_consume( 'websocket.receive', self._build_message('testmodel', { 'action': 'delete', 'pk': -1, 'request_id': 'client-request-id' })) expected = { 'action': 'delete', 'errors': ['Not found.'], 'data': None, 'request_id': 'client-request-id', 'response_status': 404 } self.assertEqual(json_content['payload'], expected) def test_list(self): for n in range(api_settings.DEFAULT_PAGE_SIZE + 1): TestModel.objects.create(name='Name-{}'.format(str(n))) json_content = self._send_and_consume( 'websocket.receive', self._build_message( 'testmodel', { 'action': 'list', 'request_id': 'client-request-id', 'data': None, })) self.assertEqual(len(json_content['payload']['data']), api_settings.DEFAULT_PAGE_SIZE) json_content = self._send_and_consume( 'websocket.receive', self._build_message( 'testmodel', { 'action': 'list', 'request_id': 'client-request-id', 'data': { 'page': 2 } })) self.assertEqual(len(json_content['payload']['data']), 1) self.assertEqual('client-request-id', json_content['payload']['request_id']) def test_retrieve(self): instance = TestModel.objects.create(name="Test") json_content = self._send_and_consume( 'websocket.receive', self._build_message( 'testmodel', { 'action': 'retrieve', 'pk': instance.id, 'request_id': 'client-request-id' })) expected = { 'action': 'retrieve', 'data': TestModelSerializer(instance).data, 'errors': [], 'response_status': 200, 'request_id': 'client-request-id' } self.assertTrue(json_content['payload'] == expected) def test_retrieve_404(self): json_content = self._send_and_consume( 'websocket.receive', self._build_message('testmodel', { 'action': 'retrieve', 'pk': 1, 'request_id': 'client-request-id' })) expected = { 'action': 'retrieve', 'data': None, 'errors': ['Not found.'], 'response_status': 404, 'request_id': 'client-request-id' } self.assertEqual(json_content['payload'], expected) def test_retrieve_invalid_pk_404(self): json_content = self._send_and_consume( 'websocket.receive', self._build_message( 'testmodel', { 'action': 'retrieve', 'pk': 'invalid-pk-value', 'request_id': 'client-request-id' })) expected = { 'action': 'retrieve', 'data': None, 'errors': ['Not found.'], 'response_status': 404, 'request_id': 'client-request-id' } self.assertEqual(json_content['payload'], expected) def test_subscribe(self): json_content = self._send_and_consume( 'websocket.receive', self._build_message( "testmodel", { 'action': 'subscribe', 'data': { 'action': 'create' }, 'request_id': 'client-request-id' })) expected_response = { 'action': 'subscribe', 'request_id': 'client-request-id', 'data': { 'action': 'create' }, 'errors': [], 'response_status': 200 } self.assertEqual(json_content['payload'], expected_response) # it should be on the create group instance = TestModel.objects.create(name='test-name') expected = { 'action': 'create', 'data': TestModelSerializer(instance).data, 'model': 'tests.testmodel', 'pk': instance.id } actual = self._get_next_message() self.assertEqual(expected, actual['payload']) def test_subscribe_failure(self): json_content = self._send_and_consume( 'websocket.receive', self._build_message( 'testmodel', { 'action': 'subscribe', 'data': {}, 'request_id': 'client-request-id' })) expected = { 'action': 'subscribe', 'data': None, 'errors': ['action required'], 'request_id': 'client-request-id', 'response_status': 400 } self.assertEqual(expected, json_content['payload']) def test_update(self): instance = TestModel.objects.create(name='some-test') json_content = self._send_and_consume( 'websocket.receive', self._build_message( 'testmodel', { 'action': 'update', 'pk': instance.id, 'data': { 'name': 'some-value' }, 'request_id': 'client-request-id' })) instance.refresh_from_db() expected = { 'action': 'update', 'errors': [], 'data': TestModelSerializer(instance).data, 'response_status': 200, 'request_id': 'client-request-id' } self.assertEqual(json_content['payload'], expected) def test_update_failure(self): instance = TestModel.objects.create(name='some-test') json_content = self._send_and_consume( 'websocket.receive', self._build_message( 'testmodel', { 'action': 'update', 'pk': -1, 'data': { 'name': 'some-value' }, 'request_id': 'client-request-id' })) expected = { 'data': None, 'action': 'update', 'errors': ['Not found.'], 'response_status': 404, 'request_id': 'client-request-id' } self.assertEqual(json_content['payload'], expected) def test_list_action(self): json_content = self._send_and_consume( 'websocket.receive', self._build_message( 'testmodel', { 'action': 'test_list', 'pk': None, 'data': {}, 'request_id': 'client-request-id', })) expected = { 'action': 'test_list', 'errors': [], 'data': 'some data', 'response_status': 200, 'request_id': 'client-request-id' } self.assertEqual(json_content['payload'], expected) def test_detail_action(self): instance = TestModel.objects.create(name='some-test') json_content = self._send_and_consume( 'websocket.receive', self._build_message( 'testmodel', { 'action': 'test_detail', 'pk': instance.id, 'data': {}, 'request_id': 'client-request-id' })) expected = { 'action': 'test_detail', 'errors': [], 'data': instance.name, 'response_status': 200, 'request_id': 'client-request-id' } self.assertEqual(json_content['payload'], expected) def test_named_list_action(self): json_content = self._send_and_consume( 'websocket.receive', self._build_message( 'testmodel', { 'action': 'named_list', 'pk': None, 'data': {}, 'request_id': 'client-request-id', })) expected = { 'action': 'named_list', 'errors': [], 'data': 'some data', 'response_status': 200, 'request_id': 'client-request-id' } self.assertEqual(json_content['payload'], expected) def test_named_detail_action(self): instance = TestModel.objects.create(name='some-test') json_content = self._send_and_consume( 'websocket.receive', self._build_message( 'testmodel', { 'action': 'named_detail', 'pk': instance.id, 'data': {}, 'request_id': 'client-request-id' })) expected = { 'action': 'named_detail', 'errors': [], 'data': instance.name, 'response_status': 200, 'request_id': 'client-request-id' } self.assertEqual(json_content['payload'], expected)
def setUp(self): super().setUp() self.client = Client()
class TestStreamConsumer(SocialhomeChannelTestCase): @classmethod def setUpTestData(cls): super().setUpTestData() cls.user = UserFactory() cls.content = ContentFactory() cls.content2 = ContentFactory() cls.child_content = ContentFactory(parent=cls.content) cls.tag = TagFactory() def setUp(self): super().setUp() self.client = Client() @patch.object(StreamConsumer, "__init__", return_value=None) @patch("socialhome.streams.consumers.PublicStream.get_queryset", return_value="spam") def test__get_base_qs(self, mock_qs, mock_consumer): consumer = StreamConsumer() consumer.kwargs = {"stream": "public"} self.assertEqual(consumer._get_base_qs(), "spam") @patch.object(StreamConsumer, "__init__", return_value=None) def test__get_stream_class(self, mock_consumer): consumer = StreamConsumer() with patch.object(consumer, "_get_stream_info", return_value=("public", None)): self.assertEqual(consumer._get_stream_class(), PublicStream) with patch.object(consumer, "_get_stream_info", return_value=("followed", None)): self.assertEqual(consumer._get_stream_class(), FollowedStream) with patch.object(consumer, "_get_stream_info", return_value=("tag", None)): self.assertEqual(consumer._get_stream_class(), TagStream) @patch.object(StreamConsumer, "__init__", return_value=None) def test__get_stream_info(self, mock_consumer): consumer = StreamConsumer() consumer.kwargs = {"stream": "spam"} self.assertEqual(consumer._get_stream_info(), ("spam", None)) consumer.kwargs = {"stream": "spam__eggs"} self.assertEqual(consumer._get_stream_info(), ("spam", "eggs")) @patch.object(StreamConsumer, "__init__", return_value=None) def test__get_stream_instance(self, mock_consumer): consumer = StreamConsumer() consumer.kwargs = {"stream": "public"} instance = consumer._get_stream_instance() self.assertTrue(isinstance(instance, PublicStream)) consumer.kwargs = {"stream": "followed"} consumer.message = Mock(user=self.user) instance = consumer._get_stream_instance() self.assertTrue(isinstance(instance, FollowedStream)) self.assertTrue(instance.user, self.user) consumer.kwargs = {"stream": "tag__%s" % self.tag.id} instance = consumer._get_stream_instance() self.assertTrue(isinstance(instance, TagStream)) self.assertEqual(instance.tag, self.tag) @patch.object(StreamConsumer, "__init__", return_value=None) @patch("socialhome.streams.consumers.PublicStream.get_content", return_value="spam") def test__get_stream_qs(self, mock_qs, mock_consumer): consumer = StreamConsumer() consumer.kwargs = {"stream": "public"} self.assertEqual(consumer._get_stream_qs(), "spam") def test_receive_load_content_sends_reply_content(self): self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/public/", "text": '{"action": "load_content", "ids": [%s]}' % self.content.id, }, ) receive = self.client.receive() text = json.loads(receive["text"]) self.assertEqual(text["event"], "content") self.assertEqual(text["placement"], "prepended") self.assertEqual(text["contents"], [self.content.dict_for_view(AnonymousUser())]) def test_receive_load_more_sends_more_content(self): self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/public/", "text": '{"action": "load_more", "last_id": %s}' % self.content2.id, }, ) receive = self.client.receive() text = json.loads(receive["text"]) self.assertEqual(text["event"], "content") self.assertEqual(text["placement"], "appended") self.assertEqual(text["contents"], [self.content.dict_for_view(AnonymousUser())]) def test_receive_load_children_sends_reply_content(self): self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/public/", "text": '{"action": "load_children", "content_id": %s}' % self.content.id, }, ) receive = self.client.receive() text = json.loads(receive["text"]) self.assertEqual(text["event"], "content") self.assertEqual(text["placement"], "children") self.assertEqual(text["parent_id"], self.content.id) self.assertEqual(text["contents"], [self.child_content.dict_for_view(AnonymousUser())]) @patch("socialhome.streams.consumers.Content.objects.public", return_value=Content.objects.none()) @patch("socialhome.streams.consumers.Content.objects.tag", return_value=Content.objects.none()) @patch("socialhome.streams.consumers.Content.objects.profile_by_id", return_value=Content.objects.none()) @patch("socialhome.streams.consumers.Content.objects.profile_pinned", return_value=Content.objects.none()) @patch("socialhome.streams.consumers.Content.objects.followed", return_value=Content.objects.none()) def test_get_stream_qs_per_stream(self, mock_followed, mock_pinned, mock_profile, mock_tag, mock_public): self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/public/", "text": '{"action": "load_more", "last_id": %s}' % self.content2.id, }, ) mock_public.assert_called_once_with() self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/tag__%s_%s/" % (self.tag.id, self.tag.name), "text": '{"action": "load_more", "last_id": %s}' % self.content2.id, }, ) self.assertEqual(mock_tag.call_count, 1) self.assertEqual(mock_tag.call_args[0][0], self.tag) self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/profile__1234/", "text": '{"action": "load_more", "last_id": %s}' % self.content2.id, }, ) self.assertEqual(mock_pinned.call_count, 1) self.assertEqual(mock_pinned.call_args[0][0], "1234") self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/profile_all__1234/", "text": '{"action": "load_more", "last_id": %s}' % self.content2.id, }, ) self.assertEqual(mock_profile.call_count, 1) self.assertEqual(mock_profile.call_args[0][0], "1234") self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/followed__foobar/", "text": '{"action": "load_more", "last_id": %s}' % self.content2.id, }, ) self.assertEqual(mock_followed.call_count, 1)
def setUp(self): super(TestStreamConsumerReceive, self).setUp() self.client = Client()
def test_simple_as_route_method(self): class WebsocketConsumer(websockets.WebsocketConsumer): def connect(self, message, **kwargs): self.send(text=message.get('order')) routes = [ WebsocketConsumer.as_route(attrs={"strict_ordering": True}, path='^/path$'), WebsocketConsumer.as_route(path='^/path/2$'), ] self.assertIsNot(routes[0].consumer, WebsocketConsumer) self.assertIs(routes[1].consumer, WebsocketConsumer) with apply_routes(routes): client = Client() client.send('websocket.connect', {'path': '/path', 'order': 1}) client.send('websocket.connect', {'path': '/path', 'order': 0}) client.consume('websocket.connect') client.consume('websocket.connect') client.consume('websocket.connect') self.assertEqual(client.receive(), {'text': 0}) self.assertEqual(client.receive(), {'text': 1}) client.send_and_consume('websocket.connect', {'path': '/path/2', 'order': 'next'}) self.assertEqual(client.receive(), {'text': 'next'})
class TestStreamConsumerReceive(ChannelTestCase): @classmethod def setUpTestData(cls): super(TestStreamConsumerReceive, cls).setUpTestData() cls.content = ContentFactory() cls.content2 = ContentFactory() def setUp(self): super(TestStreamConsumerReceive, self).setUp() self.client = Client() def test_receive_load_content_sends_reply_content(self): self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/public/", "text": '{"action": "load_content", "ids": [%s]}' % self.content.id, }, ) receive = self.client.receive() text = json.loads(receive["text"]) self.assertEqual(text["event"], "content") self.assertEqual(text["placement"], "prepended") self.assertEqual(text["contents"], [ { "id": self.content.id, "guid": self.content.guid, "author": self.content.author.id, "author_image": self.content.author.safer_image_url_small, "author_name": self.content.author.handle, "rendered": self.content.rendered, "humanized_timestamp": self.content.humanized_timestamp, "formatted_timestamp": self.content.formatted_timestamp, } ]) def test_receive_load_more_sends_more_content(self): self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/public/", "text": '{"action": "load_more", "last_id": %s}' % self.content2.id, }, ) receive = self.client.receive() text = json.loads(receive["text"]) self.assertEqual(text["event"], "content") self.assertEqual(text["placement"], "appended") self.assertEqual(text["contents"], [ { "id": self.content.id, "guid": self.content.guid, "author": self.content.author.id, "author_image": self.content.author.safer_image_url_small, "author_name": self.content.author.handle, "rendered": self.content.rendered, "humanized_timestamp": self.content.humanized_timestamp, "formatted_timestamp": self.content.formatted_timestamp, } ]) @patch("socialhome.streams.consumers.Content.objects.public", return_value=Content.objects.none()) @patch("socialhome.streams.consumers.Content.objects.tags", return_value=Content.objects.none()) @patch("socialhome.streams.consumers.Content.objects.profile", return_value=Content.objects.none()) def test_get_stream_qs_per_stream(self, mock_profile, mock_tags, mock_public): self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/public/", "text": '{"action": "load_more", "last_id": %s}' % self.content2.id, }, ) mock_public.assert_called_once_with() self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/tags__foobar/", "text": '{"action": "load_more", "last_id": %s}' % self.content2.id, }, ) self.assertEqual(mock_tags.call_count, 1) self.assertEqual(mock_tags.call_args[0][0], "foobar") self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/profile__1234/", "text": '{"action": "load_more", "last_id": %s}' % self.content2.id, }, ) self.assertEqual(mock_profile.call_count, 1) self.assertEqual(mock_profile.call_args[0][0], "1234")
def test_websockets_demultiplexer(self): class MyWebsocketConsumer(websockets.JsonWebsocketConsumer): def connect(self, message, multiplexer=None, **kwargs): multiplexer.send(kwargs) def disconnect(self, message, multiplexer=None, **kwargs): multiplexer.send(kwargs) def receive(self, content, multiplexer=None, **kwargs): multiplexer.send(content) class Demultiplexer(websockets.WebsocketDemultiplexer): consumers = {"mystream": MyWebsocketConsumer} with apply_routes([ route_class(Demultiplexer, path='/path/(?P<id>\d+)'), route_class(MyWebsocketConsumer), ]): client = Client() client.send_and_consume('websocket.connect', {'path': '/path/1'}) self.assertEqual( client.receive(), { "text": json.dumps({ "stream": "mystream", "payload": { "id": "1" }, }) }) client.send_and_consume( 'websocket.receive', { 'path': '/path/1', 'text': json.dumps({ "stream": "mystream", "payload": { "text_field": "mytext" } }) }) self.assertEqual( client.receive(), { "text": json.dumps({ "stream": "mystream", "payload": { "text_field": "mytext" }, }) }) client.send_and_consume('websocket.disconnect', {'path': '/path/1'}) self.assertEqual( client.receive(), { "text": json.dumps({ "stream": "mystream", "payload": { "id": "1" }, }) })
def test_simple_as_route_method(self): class WebsocketConsumer(websockets.WebsocketConsumer): def connect(self, message, **kwargs): self.send(text=message.get('order')) routes = [ WebsocketConsumer.as_route(attrs={'slight_ordering': True}, path='^/path$'), WebsocketConsumer.as_route(path='^/path/2$'), ] self.assertIsNot(routes[0].consumer, WebsocketConsumer) self.assertIs(routes[1].consumer, WebsocketConsumer) with apply_routes(routes): client = Client() client.send('websocket.connect', {'path': '/path', 'order': 1}) client.send('websocket.connect', {'path': '/path', 'order': 0}) client.consume('websocket.connect') client.consume('websocket.connect') client.consume('websocket.connect') self.assertEqual(client.receive(), {'text': 0}) self.assertEqual(client.receive(), {'text': 1}) client.send_and_consume('websocket.connect', { 'path': '/path/2', 'order': 'next' }) self.assertEqual(client.receive(), {'text': 'next'})
class TestStreamConsumerReceive(ChannelTestCase): maxDiff = None @classmethod def setUpTestData(cls): super(TestStreamConsumerReceive, cls).setUpTestData() cls.content = ContentFactory() cls.content2 = ContentFactory() cls.child_content = ContentFactory(parent=cls.content) cls.tag = TagFactory() def setUp(self): super(TestStreamConsumerReceive, self).setUp() self.client = Client() def test_receive_load_content_sends_reply_content(self): self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/public/", "text": '{"action": "load_content", "ids": [%s]}' % self.content.id, }, ) receive = self.client.receive() text = json.loads(receive["text"]) self.assertEqual(text["event"], "content") self.assertEqual(text["placement"], "prepended") self.assertEqual(text["contents"], [self.content.dict_for_view(AnonymousUser())]) def test_receive_load_more_sends_more_content(self): self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/public/", "text": '{"action": "load_more", "last_id": %s}' % self.content2.id, }, ) receive = self.client.receive() text = json.loads(receive["text"]) self.assertEqual(text["event"], "content") self.assertEqual(text["placement"], "appended") self.assertEqual(text["contents"], [self.content.dict_for_view(AnonymousUser())]) def test_receive_load_children_sends_reply_content(self): self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/public/", "text": '{"action": "load_children", "content_id": %s}' % self.content.id, }, ) receive = self.client.receive() text = json.loads(receive["text"]) self.assertEqual(text["event"], "content") self.assertEqual(text["placement"], "children") self.assertEqual(text["parent_id"], self.content.id) self.assertEqual(text["contents"], [self.child_content.dict_for_view(AnonymousUser())]) @patch("socialhome.streams.consumers.Content.objects.public", return_value=Content.objects.none()) @patch("socialhome.streams.consumers.Content.objects.tag", return_value=Content.objects.none()) @patch("socialhome.streams.consumers.Content.objects.profile_by_id", return_value=Content.objects.none()) @patch("socialhome.streams.consumers.Content.objects.profile_pinned", return_value=Content.objects.none()) @patch("socialhome.streams.consumers.Content.objects.followed", return_value=Content.objects.none()) def test_get_stream_qs_per_stream(self, mock_followed, mock_pinned, mock_profile, mock_tag, mock_public): self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/public/", "text": '{"action": "load_more", "last_id": %s}' % self.content2.id, }, ) mock_public.assert_called_once_with() self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/tag__%s_%s/" % (self.tag.id, self.tag.name), "text": '{"action": "load_more", "last_id": %s}' % self.content2.id, }, ) self.assertEqual(mock_tag.call_count, 1) self.assertEqual(mock_tag.call_args[0][0], self.tag) self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/profile__1234/", "text": '{"action": "load_more", "last_id": %s}' % self.content2.id, }, ) self.assertEqual(mock_pinned.call_count, 1) self.assertEqual(mock_pinned.call_args[0][0], "1234") self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/profile_all__1234/", "text": '{"action": "load_more", "last_id": %s}' % self.content2.id, }, ) self.assertEqual(mock_profile.call_count, 1) self.assertEqual(mock_profile.call_args[0][0], "1234") self.client.send_and_consume( "websocket.receive", { "path": "/ch/streams/followed__foobar/", "text": '{"action": "load_more", "last_id": %s}' % self.content2.id, }, ) self.assertEqual(mock_followed.call_count, 1)