Exemplo n.º 1
0
    def test_inbound_delete(self):
        user = User.objects.create(username='******', email='*****@*****.**')

        class Demultiplexer(WebsocketDemultiplexer):
            mapping = {
                'users': 'binding.users',
            }

            groups = ['inbound']

        class UserBinding(WebsocketBinding):
            model = User
            stream = 'users'
            fields = ['username', ]

            @classmethod
            def group_names(cls, instance, action):
                return ['users_outbound']

            def has_permission(self, user, action, pk):
                return True

        with apply_routes([Demultiplexer.as_route(path='/'), route('binding.users', UserBinding.consumer)]):
            client = HttpClient()
            client.send_and_consume('websocket.connect', path='/')
            client.send_and_consume('websocket.receive', path='/', text={
                'stream': 'users',
                'payload': {'action': DELETE, 'pk': user.pk}
            })
            # our Demultiplexer route message to the inbound consumer, so call Demultiplexer consumer
            client.consume('binding.users')

        self.assertIsNone(User.objects.filter(pk=user.pk).first())
        self.assertIsNone(client.receive())
Exemplo n.º 2
0
    def test_simple_as_route_method(self):
        class WebsocketConsumer(websockets.WebsocketConsumer):
            def connect(self, message, **kwargs):
                self.message.reply_channel.send({'accept': True})
                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 = HttpClient()

            client.send('websocket.connect', {'path': '/path', 'order': 1})
            client.send('websocket.connect', {'path': '/path', 'order': 0})
            client.consume('websocket.connect', check_accept=False)
            client.consume('websocket.connect')
            self.assertEqual(client.receive(json=False), 0)
            client.consume('websocket.connect')
            self.assertEqual(client.receive(json=False), 1)

            client.send_and_consume('websocket.connect', {
                'path': '/path/2',
                'order': 'next'
            })
            self.assertEqual(client.receive(json=False), 'next')
Exemplo n.º 3
0
    def test_inbound_delete(self):
        user = User.objects.create(username='******', email='*****@*****.**')

        class UserBinding(WebsocketBinding):
            model = User
            stream = 'users'
            fields = ['username', ]

            @classmethod
            def group_names(cls, instance):
                return ['users_outbound']

            def has_permission(self, user, action, pk):
                return True

        class Demultiplexer(WebsocketDemultiplexer):
            consumers = {
                'users': UserBinding.consumer,
            }

            groups = ['inbound']

        with apply_routes([Demultiplexer.as_route(path='/')]):
            client = HttpClient()
            client.send_and_consume('websocket.connect', path='/')
            client.send_and_consume('websocket.receive', path='/', text={
                'stream': 'users',
                'payload': {'action': DELETE, 'pk': user.pk}
            })

        self.assertIsNone(User.objects.filter(pk=user.pk).first())
        self.assertIsNone(client.receive())
Exemplo n.º 4
0
class MockUser:
    def __init__(self,name):
        self.client=HttpClient()
        User.objects.create_user(username=name,
            email='*****@*****.**',password='******')
        self.client.force_login(User.objects.get(username=name))
        self.client.send_and_consume('websocket.connect',path='/')
Exemplo n.º 5
0
    def test_inbound_notifications(self):
        @MyJsonRpcWebsocketConsumerTest.rpc_notification()
        def notif1(params, **kwargs):
            self.assertEqual(params, {"payload": True})

        @MyJsonRpcWebsocketConsumerTest.rpc_notification('notif.notif2')
        def notif2(params, **kwargs):
            self.assertEqual(params, {"payload": 12345})

        client = HttpClient()

        # we send a notification to the server
        client.send_and_consume(
            u'websocket.receive',
            text=
            '{"jsonrpc":"2.0", "method":"notif1", "params":[{"payload": true}]}'
        )
        msg = client.receive()
        self.assertEqual(msg, None)

        # we test with method rewriting
        client.send_and_consume(
            u'websocket.receive',
            text=
            '{"jsonrpc":"2.0", "method":"notif.notif2", "params":[{"payload": 12345}]}'
        )
        self.assertEqual(msg, None)
    def test_list_consumers(self):
        # create object
        for i in range(20):
            User.objects.create_user(username='******' + str(i), email='*****@*****.**')
        # create client
        client = HttpClient()

        with apply_routes([
                ListConsumers.as_routes(model=User,
                                        path='/',
                                        channel_name='test',
                                        paginate_by=10)
        ]):
            client.send_and_consume(u'websocket.connect', {'path': '/'})
            client.send_and_consume(u'websocket.receive', {
                'path': '/',
                'action': 'list',
                'page': 2
            })
            client.consume('test')
            rec = client.receive()
            res = json.loads(json.loads(rec['text'])['response'])

        self.assertEqual(len(res), 10)
        self.assertEqual(res[0]['username'], 'test10')
        self.assertEqual(res[0]['email'], '*****@*****.**')
        self.assertEqual(res[0]['is_active'], True)
Exemplo n.º 7
0
    def test_Session(self):
        @MyJsonRpcWebsocketConsumerTest.rpc_method()
        def ping_set_session2(**kwargs):
            original_message = kwargs["original_message"]
            original_message.channel_session["test"] = True
            return "pong_set_session2"

        @MyJsonRpcWebsocketConsumerTest.rpc_method()
        def ping_get_session2(**kwargs):
            original_message = kwargs["original_message"]
            self.assertNotIn("test", original_message.channel_session)
            return "pong_get_session2"

        client = HttpClient()
        client.send_and_consume(
            u'websocket.receive',
            text=
            '{"id":1, "jsonrpc":"2.0", "method":"ping_set_session2", "params":{}}'
        )
        msg = client.receive()
        self.assertEqual(msg['result'], "pong_set_session2")

        client2 = HttpClient()
        client2.send_and_consume(
            u'websocket.receive',
            text=
            '{"id":1, "jsonrpc":"2.0", "method":"ping_get_session2", "params":{}}'
        )
        msg = client2.receive()
        self.assertEqual(msg['result'], "pong_get_session2")
    def test_update_mixin(self):
        # create object
        obj = User.objects.create_user(username='******', email='*****@*****.**')
        # create client
        client = HttpClient()

        data = {'username': '******'}
        with apply_routes([
                UpdateConsumers.as_routes(model=User,
                                          path='/(?P<pk>\d+)/?',
                                          channel_name='test')
        ]):

            client.send_and_consume('websocket.connect',
                                    {'path': '/{}'.format(obj.pk)})
            client.send_and_consume(
                'websocket.receive', {
                    'path': '/{}'.format(obj.pk),
                    'action': 'update',
                    'data': json.dumps(data)
                })
            client.consume('test')

        user = User.objects.filter(pk=obj.pk).first()
        self.assertTrue(user)
        self.assertEqual(user.username, 'new_name')
    def test_object_sub_with_subs_first(self):
        # define consumers
        routes = ObjectSubscribeConsumers.as_routes(path='/(?P<pk>\d+)/?',
                                                    model=User)
        # create client
        client = HttpClient()
        with apply_routes([routes]):
            # subscribe for object changes
            client.send_and_consume(u'websocket.connect',
                                    content={'path': '/{}'.format('1')})

            # create object
            User.objects.create_user(username='******', email='*****@*****.**')
            res = json.loads(client.receive()['text'])
            self.assertTrue('data' in res.keys())
            self.assertTrue('action' in res.keys())
            self.assertTrue(res['action'] == 'created')
            data = res['data']
            self.assertEqual(data['username'], 'test')
            self.assertEqual(data['is_active'], True)
            self.assertEqual(data['email'], '*****@*****.**')
            self.assertEqual(data['is_staff'], False)

            # check that nothing happened
            self.assertIsNone(client.receive())
Exemplo n.º 10
0
    def test_simple_as_route_method(self):

        class WebsocketConsumer(websockets.WebsocketConsumer):

            def connect(self, message, **kwargs):
                self.message.reply_channel.send({'accept': True})
                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 = HttpClient()

            client.send('websocket.connect', {'path': '/path', 'order': 1})
            client.send('websocket.connect', {'path': '/path', 'order': 0})
            client.consume('websocket.connect', check_accept=False)
            client.consume('websocket.connect')
            self.assertEqual(client.receive(json=False), 0)
            client.consume('websocket.connect')
            self.assertEqual(client.receive(json=False), 1)

            client.send_and_consume('websocket.connect', {'path': '/path/2', 'order': 'next'})
            self.assertEqual(client.receive(json=False), 'next')
Exemplo n.º 11
0
    def test_model_sub(self):
        # define consumers
        routes = ModelSubscribeConsumers.as_routes(model=User)
        # create client
        client = HttpClient()

        # create object
        user = User.objects.create_user(username='******', email='*****@*****.**')

        with apply_routes([routes]):
            # subscribe for Models changes
            client.send_and_consume(u'websocket.connect')

            # change object
            user.username = '******'
            user.save()

            res = json.loads(client.receive()['text'])
            self.assertEqual(res['action'], 'updated')
            self.assertEqual(res['data']['username'], 'new username')
            self.assertEqual(res['data']['email'], '*****@*****.**')

            # create new one
            to_del = User.objects.create_user(username='******', email='*****@*****.**')
            res = json.loads(client.receive()['text'])
            self.assertEqual(res['action'], 'created')
            self.assertEqual(res['data']['username'], 'test2')
            self.assertEqual(res['data']['email'], '*****@*****.**')

            # delete
            to_del.delete()
            res = json.loads(client.receive()['text'])
            self.assertEqual(res['action'], 'deleted')
            self.assertEqual(res['data']['username'], 'test2')
            self.assertEqual(res['data']['email'], '*****@*****.**')
Exemplo n.º 12
0
    def test_demultiplexer(self):
        class Demultiplexer(WebsocketDemultiplexer):
            mapping = {
                'users': 'binding.users',
            }

            groups = ['inbound']

        with apply_routes([Demultiplexer.as_route(path='/')]):
            client = HttpClient()
            client.send_and_consume('websocket.connect', path='/')

            # assert in group
            Group('inbound').send({'text': json.dumps({'test': 'yes'})},
                                  immediately=True)
            self.assertEqual(client.receive(), {'test': 'yes'})

            # assert that demultiplexer stream message
            client.send_and_consume('websocket.receive',
                                    path='/',
                                    text={
                                        'stream': 'users',
                                        'payload': {
                                            'test': 'yes'
                                        }
                                    })
            message = client.get_next_message('binding.users')
            self.assertIsNotNone(message)
            self.assertEqual(message.content['test'], 'yes')
Exemplo n.º 13
0
    def test_original_message_position_safe(self):
        @MyJsonRpcWebsocketConsumerTest.rpc_method()
        def ping_set_session(name, value, **kwargs):
            original_message = kwargs["original_message"]
            original_message.channel_session["test"] = True
            return ["pong_set_session", value, name]

        @MyJsonRpcWebsocketConsumerTest.rpc_method()
        def ping_get_session(value2, name2, **kwargs):
            original_message = kwargs["original_message"]
            self.assertEqual(original_message.channel_session["test"], True)
            return ["pong_get_session", value2, name2]

        client = HttpClient()
        client.send_and_consume(
            u'websocket.receive',
            text='{"id":1, "jsonrpc":"2.0", "method":"ping_set_session", '
            '"params":["name_of_function", "value_of_function"]}')
        msg = client.receive()
        self.assertEqual(
            msg['result'],
            ["pong_set_session", "value_of_function", "name_of_function"])
        client.send_and_consume(
            u'websocket.receive',
            text='{"id":1, "jsonrpc":"2.0", "method":"ping_get_session", '
            '"params":{"name2": "name2_of_function", "value2": "value2_of_function"}}'
        )
        msg = client.receive()
        self.assertEqual(
            msg['result'],
            ["pong_get_session", "value2_of_function", "name2_of_function"])
Exemplo n.º 14
0
    def test_demultiplexer_with_wrong_payload(self):
        class Demultiplexer(WebsocketDemultiplexer):
            mapping = {
                'users': 'binding.users',
            }

            groups = ['inbound']

        with apply_routes([Demultiplexer.as_route(path='/')]):
            client = HttpClient()
            client.send_and_consume('websocket.connect', path='/')

            with self.assertRaises(ValueError) as value_error:
                client.send_and_consume('websocket.receive',
                                        path='/',
                                        text={
                                            'stream': 'users',
                                            'payload': 'test',
                                        })

            self.assertEqual(value_error.exception.args[0],
                             'Multiplexed frame payload is not a dict')

            message = client.get_next_message('binding.users')
            self.assertIsNone(message)
Exemplo n.º 15
0
    def test_custom_json_encoder(self):
        some_date = datetime.utcnow()

        @MyJsonRpcWebsocketConsumerTest.rpc_method()
        def test_method():
            return {'date': some_date}

        client = HttpClient()
        try:
            client.send_and_consume(
                u'websocket.receive',
                text=
                '{"id":1, "jsonrpc":"2.0", "method":"test_method", "params":{}}'
            )
            self.fail('Looks like test does not work')
        except TypeError:
            pass

        @DjangoJsonRpcWebsocketConsumerTest.rpc_method()
        def test_method1():
            return {'date': some_date}

        client.send_and_consume(
            u'websocket.receive',
            text=
            '{"id":1, "jsonrpc":"2.0", "method":"test_method1", "params":{}}',
            path='/django/')
        msg = client.receive()
        self.assertEqual(msg['result'], {u'date': some_date.isoformat()[:-3]})
Exemplo n.º 16
0
    def test_id_on_good_request(self):
        # Test that parsing a ping request works
        client = HttpClient()

        client.send_and_consume(
            u'websocket.receive',
            text='{"id":52, "jsonrpc":"2.0", "method":"ping", "params":{}}')
        msg = client.receive()
        self.assertEqual(msg['id'], 52)
Exemplo n.º 17
0
    def test_notification(self):
        # Test that parsing a bad request works

        client = HttpClient()

        client.send_and_consume(
            u'websocket.receive',
            text='{"jsonrpc":"2.0", "method":"a_notif", "params":{}}')
        self.assertEqual(client.receive(), None)
Exemplo n.º 18
0
    def test_parsing_with_good_request(self):
        # Test that parsing a ping request works
        client = HttpClient()

        client.send_and_consume(
            u'websocket.receive',
            text='{"id":1, "jsonrpc":"2.0", "method":"ping", "params":[false]}'
        )
        msg = client.receive()
        self.assertEquals(msg['result'], "pong")
    def test_object_sub_with_fields(self):
        # create object for subscribe
        sub_object = User.objects.create_user(username='******', email='*****@*****.**')

        # define consumers
        routes = ObjectSubscribeConsumers.as_routes(
            path='/(?P<pk>\d+)/?',
            model=User,
            serializer_kwargs={'fields': ['username', 'is_active']})

        # create client
        client = HttpClient()
        with apply_routes([routes]):
            # subscribe for object changes
            client.send_and_consume(
                u'websocket.connect',
                content={'path': '/{}'.format(sub_object.pk)})

            # change sub object
            sub_object.username = '******'
            sub_object.email = '*****@*****.**'
            sub_object.save()

            res = json.loads(client.receive()['text'])['data']
            self.assertEqual(res['username'], 'sub_object')
            self.assertEqual(res['is_active'], True)
            self.assertNotIn('email', res)
            self.assertNotIn('is_staff', res)

            sub_object.username = '******'
            sub_object.is_active = False
            sub_object.save()

            res = json.loads(client.receive()['text'])
            self.assertEqual(res['action'], 'updated')
            self.assertNotIn('email', res['data'])
            self.assertNotIn('is_staff', res['data'])

            self.assertEqual(res['data']['username'], 'test')
            self.assertEqual(res['data']['is_active'], False)

            sub_object.username = '******'
            sub_object.save(update_fields=['username'])

            res = json.loads(client.receive()['text'])
            self.assertEqual(res['action'], 'updated')
            self.assertEqual(res['data']['username'], 'test_new')
            self.assertNotIn('is_active', res['data'])
            self.assertNotIn('is_staff', res['data'])

            sub_object.email = '*****@*****.**'
            sub_object.save(update_fields=['email'])

            # check that nothing happened
            self.assertIsNone(client.receive())
Exemplo n.º 20
0
    def test_websocket_param_in_decorator_for_notification(self):
        @MyJsonRpcWebsocketConsumerTest.rpc_notification(websocket=False)
        def ping():
            return "pong"

        client = HttpClient()
        client.send_and_consume(u'websocket.receive',
                                text='{"jsonrpc":"2.0", "method":"ping", '
                                '"params":[]}')
        msg = client.receive()
        self.assertEqual(msg, None)
Exemplo n.º 21
0
 def test_create_appointment_celery_task_send_notification_to_user(self):
     self._create_appointment()
     client = HttpClient()
     client.send_and_consume(
         "websocket.connect",
         path="/?auth_token=%s" % self._get_token_for(self.simple_user)
     )
     msg = client.receive()
     self.assertEquals(msg.get('action'),
                       'appointment_timeout_expired')
     self.assertIn('appointment', msg.get('message'))
Exemplo n.º 22
0
 def test_create_appointment_admin_receive_notification_after_connect(
         self, *args):
     self._create_appointment()
     time.sleep(1)
     client = HttpClient()
     client.send_and_consume(
         "websocket.connect",
         path="/?auth_token=%s" % self._get_token_for(self.clinic_admin1)
     )
     msg = client.receive()
     self.assertEquals(msg.get('action'), 'appointment_created')
     self.assertTrue(msg.get('message'))
Exemplo n.º 23
0
 def test_create_appointment_notification_expired(self, *args):
     c, r, appointment = self._create_appointment()
     user_notif = UserNotification.objects.get(user=self.clinic_admin1)
     user_notif.expired = F('expired') - timedelta(seconds=58)
     user_notif.save(update_fields=['expired', ])
     time.sleep(2)
     client = HttpClient()
     client.send_and_consume(
         "websocket.connect",
         path="/?auth_token=%s" % self._get_token_for(self.clinic_admin1)
     )
     self.assertIsNone(client.receive())
Exemplo n.º 24
0
    def test_create_mixin(self):
        # create client
        client = HttpClient()
        data = {'username': '******', 'email': '*****@*****.**'}

        with apply_routes([CreateConsumers.as_routes(model=User, path='/', channel_name='test')]):
            client.send_and_consume(u'websocket.connect', {'path': '/'})
            client.send_and_consume(u'websocket.receive', {'path': '/', 'action': 'create',
                                                           'data': json.dumps(data)})
            client.consume(u'test')

        self.assertTrue(User.objects.filter(username='******', email='*****@*****.**').exists())
Exemplo n.º 25
0
 def test_create_appointment_celery_task_send_notification_to_admin(self):
     client = HttpClient()
     client.send_and_consume(
         "websocket.connect",
         path="/?auth_token=%s" % self._get_token_for(self.clinic_admin1)
     )
     self._create_appointment()
     msg = client.receive()  # first message about creating request
     msg = client.receive()
     self.assertEquals(msg.get('action'),
                       'appointment_timeout_expired')
     self.assertIn('appointment_event', msg.get('message'))
Exemplo n.º 26
0
    def test_websocket_param_in_decorator_for_method(self):
        @MyJsonRpcWebsocketConsumerTest.rpc_method(websocket=False)
        def ping():
            return "pong"

        client = HttpClient()
        client.send_and_consume(
            u'websocket.receive',
            text='{"id":1, "jsonrpc":"2.0", "method":"ping", '
            '"params":[]}')
        msg = client.receive()
        self.assertEqual(msg['error']['message'], "Method Not Found")
Exemplo n.º 27
0
 def test_admin_suggested_another_time_patient_receive_notification(
         self, *args):
     c, r, appointment = self._create_appointment()
     self._suggest(appointment, self.clinic_admin1)
     client = HttpClient()
     client.send_and_consume(
         "websocket.connect",
         path="/?auth_token=%s" % self._get_token_for(self.simple_user)
     )
     msg = client.receive()
     self.assertEquals(msg.get('action'), 'appointment_clinic_suggested')
     self.assertTrue(msg.get('message'))
Exemplo n.º 28
0
    def test_delete_mixin(self):
        # create object
        obj = User.objects.create_user(username='******', email='*****@*****.**')
        # create client
        client = HttpClient()

        with apply_routes([DeleteConsumers.as_routes(model=User, path='/(?P<pk>\d+)/?', channel_name='test')]):
            client.send_and_consume(u'websocket.connect', {'path': '/{}'.format(obj.pk)})
            client.send_and_consume(u'websocket.receive', {'path': '/{}'.format(obj.pk), 'action': 'delete'})
            client.consume('test')

        self.assertFalse(User.objects.filter(pk=obj.pk).exists())
Exemplo n.º 29
0
    def test_method(self):
        @MyJsonRpcWebsocketConsumerTest.rpc_method()
        def ping2():
            return "pong2"

        client = HttpClient()
        client.send_and_consume(
            u'websocket.receive',
            text='{"id":1, "jsonrpc":"2.0", "method":"ping2", "params":{}}')

        msg = client.receive()

        self.assertEqual(msg['result'], "pong2")
Exemplo n.º 30
0
 def test_one_admin_suggested_others_receive_notification_about_inactive(
         self, *args):
     client = HttpClient()
     client.send_and_consume(
         "websocket.connect",
         path="/?auth_token=%s" % self._get_token_for(self.clinic_admin2)
     )
     c, r, appointment = self._create_appointment()
     self._suggest(appointment, self.clinic_admin1)
     msg = client.receive()  # first message about creating
     msg = client.receive()
     self.assertEquals(msg.get('action'), 'appointment_inactive')
     self.assertTrue(msg.get('message'))
Exemplo n.º 31
0
    def test_error_on_notification_frame(self):
        @MyJsonRpcWebsocketConsumerTest.rpc_method()
        def ping():
            return True

        client = HttpClient()

        # we send a notification to the server
        client.send_and_consume(
            u'websocket.receive',
            text='{"jsonrpc":"2.0", "method":"dwqwdq", "params":[]}')
        msg = client.receive()
        self.assertEqual(msg, None)
Exemplo n.º 32
0
    def test_kwargs_not_there(self):
        @MyJsonRpcWebsocketConsumerTest.rpc_method()
        def ping():
            return True

        client = HttpClient()

        # we send a notification to the server
        client.send_and_consume(
            u'websocket.receive',
            text='{"id":1, "jsonrpc":"2.0", "method":"ping", "params":[]}')
        msg = client.receive()
        self.assertEqual(msg["result"], True)
Exemplo n.º 33
0
    def test_object_sub_with_fields(self):
        # create object for subscribe
        sub_object = User.objects.create_user(username='******', email='*****@*****.**')

        # define consumers
        routes = ObjectSubscribeConsumers.as_routes(path='/(?P<pk>\d+)/?', model=User,
                                                    serializer_kwargs={'fields': ['username', 'is_active']})

        # create client
        client = HttpClient()
        with apply_routes([routes]):
            # subscribe for object changes
            client.send_and_consume(u'websocket.connect', content={'path': '/{}'.format(sub_object.pk)})

            # change sub object
            sub_object.username = '******'
            sub_object.email = '*****@*****.**'
            sub_object.save()

            res = json.loads(client.receive()['text'])['data']
            self.assertEqual(res['username'], 'sub_object')
            self.assertEqual(res['is_active'], True)
            self.assertNotIn('email', res)
            self.assertNotIn('is_staff', res)

            sub_object.username = '******'
            sub_object.is_active = False
            sub_object.save()

            res = json.loads(client.receive()['text'])
            self.assertEqual(res['action'], 'updated')
            self.assertNotIn('email', res['data'])
            self.assertNotIn('is_staff', res['data'])

            self.assertEqual(res['data']['username'], 'test')
            self.assertEqual(res['data']['is_active'], False)

            sub_object.username = '******'
            sub_object.save(update_fields=['username'])

            res = json.loads(client.receive()['text'])
            self.assertEqual(res['action'], 'updated')
            self.assertEqual(res['data']['username'], 'test_new')
            self.assertNotIn('is_active', res['data'])
            self.assertNotIn('is_staff', res['data'])

            sub_object.email = '*****@*****.**'
            sub_object.save(update_fields=['email'])

            # check that nothing happened
            self.assertIsNone(client.receive())
Exemplo n.º 34
0
 def test_appointment_confirmed_push_notification_should_sent_to_user(
         self, *args):
     client = HttpClient()
     client.send_and_consume(
         "websocket.connect",
         path="/?auth_token=%s" % self._get_token_for(self.simple_user)
     )
     with mock.patch('clinicapp.pkg.notifications.messenger.Messenger.'
                     'send_push_notifications') as push_call:
         c, r, appointment = self._create_appointment()
         c, r, event = self._accept(appointment, self.clinic_admin1)
         AppointmentActions(event.appointment).confirm(event)
         self.assertEquals(push_call.call_count, 1)
         self.assertEquals(push_call.call_args[0][0], self.simple_user)
Exemplo n.º 35
0
    def test_after_reopen_clinic_admins_receive_notification(self, *args):
        c, r, appointment = self._create_appointment()
        AppointmentActions(appointment).timeout()

        self._reopen(appointment.pk)

        client = HttpClient()
        client.send_and_consume(
            "websocket.connect",
            path="/?auth_token=%s" % self._get_token_for(self.clinic_admin1)
        )
        msg = client.receive()
        self.assertEquals(msg.get('action'), 'appointment_created')
        self.assertTrue(msg.get('message', {}).get('appointment_event'))
Exemplo n.º 36
0
 def test_user_not_payment_admin_receive_appointment_canceled_after_timeout(
         self, *args):
     client = HttpClient()
     client.send_and_consume(
         "websocket.connect",
         path="/?auth_token=%s" % self._get_token_for(self.clinic_admin1)
     )
     c, r, appointment = self._create_appointment()
     self._accept(appointment, self.clinic_admin1)
     msg = client.receive()  # first message about creating
     msg = client.receive()
     self.assertEquals(msg.get('action'),
                       'appointment_canceled')
     self.assertIn('appointment_event', msg.get('message'))
Exemplo n.º 37
0
    def test_get_mixin(self):
        # create object
        obj = User.objects.create_user(username='******', email='*****@*****.**')
        # create client
        client = HttpClient()

        with apply_routes([ReadOnlyConsumers.as_routes(model=User, path='/(?P<pk>\d+)/?', channel_name='test')]):

            client.send_and_consume(u'websocket.connect', {'path': '/{}'.format(obj.pk)})
            client.send_and_consume(u'websocket.receive', {'path': '/{}'.format(obj.pk), 'action': 'get'})
            client.consume('test')
            res = json.loads(json.loads(client.receive()['text'])['response'])

            self.assertEqual(res['username'], 'test')
            self.assertEqual(res['email'], '*****@*****.**')
            self.assertEqual(res['is_active'], True)
Exemplo n.º 38
0
    def test_update_mixin(self):
        # create object
        obj = User.objects.create_user(username='******', email='*****@*****.**')
        # create client
        client = HttpClient()

        data = {'username': '******'}
        with apply_routes([UpdateConsumers.as_routes(model=User, path='/(?P<pk>\d+)/?', channel_name='test')]):

            client.send_and_consume('websocket.connect', {'path': '/{}'.format(obj.pk)})
            client.send_and_consume('websocket.receive', {'path': '/{}'.format(obj.pk), 'action': 'update',
                                                          'data': json.dumps(data)})
            client.consume('test')

        user = User.objects.filter(pk=obj.pk).first()
        self.assertTrue(user)
        self.assertEqual(user.username, 'new_name')
Exemplo n.º 39
0
    def test_filters_and_routing(self):
        class Test(Consumers):
            channel_name = 'test'
            mark = 'default'

            @consumer(tag='test')
            def test(this, message):
                this.reply_channel.send({'status': 'ok'})

            @consumer('test2', tag='test')
            def test2(this, message):
                this.reply_channel.send({'status': 'ok', 'mark': this.mark})

        with apply_routes([Test.as_routes(), Test.as_routes(channel_name='test3', mark='new')]):
            client = HttpClient()
            self.assertIsNone(client.send_and_consume(u'test', content={'tag': 'tag'}, fail_on_none=False))

            client.send_and_consume(u'test', content={'tag': 'test'})

            self.assertDictEqual(client.receive(), {'status': 'ok'})
            client.consume('test', fail_on_none=False)
            self.assertIsNone(client.receive())

            client.send_and_consume(u'test3', content={'tag': 'test'})

            self.assertDictEqual(client.receive(), {'status': 'ok'})
            client.consume('test3', fail_on_none=False)
            self.assertIsNone(client.receive())

            client.send_and_consume(u'test2', content={'tag': 'test'})
            self.assertDictEqual(client.receive(), {'status': 'ok', 'mark': 'default'})
            client.consume('test2', fail_on_none=False)
            self.assertIsNone(client.receive())
Exemplo n.º 40
0
    def test_list_consumers(self):
        # create object
        for i in range(20):
            User.objects.create_user(username='******' + str(i), email='*****@*****.**')
        # create client
        client = HttpClient()

        with apply_routes([ListConsumers.as_routes(model=User, path='/', channel_name='test', paginate_by=10)]):
            client.send_and_consume(u'websocket.connect', {'path': '/'})
            client.send_and_consume(u'websocket.receive', {'path': '/', 'action': 'list', 'page': 2})
            client.consume('test')
            rec = client.receive()
            res = json.loads(json.loads(rec['text'])['response'])

        self.assertEqual(len(res), 10)
        self.assertEqual(res[0]['username'], 'test10')
        self.assertEqual(res[0]['email'], '*****@*****.**')
        self.assertEqual(res[0]['is_active'], True)
Exemplo n.º 41
0
    def test_passing_kwargs_and_reply_channel(self):

        class Test(Consumers):
            path = '^/(?P<slug>[^/]+)/(?P<pk>\d+)/?'
            channel_name = 'test'

            @consumer(tag='(?P<test>[^/]+)')
            def test(this, message, test):
                this.reply_channel.send({'test': test, 'kwargs': message.content['_kwargs']['slug'],
                                         'slug': this.kwargs.get('slug', None)})

        with apply_routes([Test.as_routes()]):
            client = HttpClient()
            client.send_and_consume(u'websocket.connect', content={'path': '/name/123/'})
            client.send_and_consume(u'websocket.receive', content={'path': '/name/123', 'tag': 'tag'})
            client.consume(u'test')
            content = client.receive()

            self.assertDictEqual(content, {'test': 'tag', 'slug': 'name', 'kwargs': 'name'})
Exemplo n.º 42
0
    def test_model_sub_with_fields(self):
        # define consumers
        routes = ModelSubscribeConsumers.as_routes(model=User,
                                                   serializer_kwargs={'fields': ['username']})
        # create client
        client = HttpClient()

        with apply_routes([routes]):
            # subscribe for Models changes
            client.send_and_consume(u'websocket.connect')

            # create object
            User.objects.create_user(username='******', email='*****@*****.**')

            res = json.loads(client.receive()['text'])
            self.assertEqual(res['action'], 'created')
            self.assertEqual(res['data']['username'], 'test')
            self.assertNotIn('is_active', res['data'])
            self.assertNotIn('email', res['data'])
Exemplo n.º 43
0
    def test_object_sub(self):

        # create object for subscribe
        sub_object = User.objects.create_user(username='******', email='*****@*****.**')

        # create object without subscribers
        just_object = User.objects.create_user(username='******', email='*****@*****.**')

        # define consumers
        routes = ObjectSubscribeConsumers.as_routes(path='/(?P<pk>\d+)/?', model=User)

        # create client
        client = HttpClient()
        with apply_routes([routes]):
            # subscribe for object changes
            client.send_and_consume(u'websocket.connect', content={'path': '/{}'.format(sub_object.pk)})

            # change sub object
            sub_object.username = '******'
            sub_object.email = '*****@*****.**'
            sub_object.save()
            res = json.loads(client.receive()['text'])
            self.assertEqual(res['action'], 'updated')
            self.assertEqual(res['data']['username'], 'sub_object')
            self.assertEqual(res['data']['email'], '*****@*****.**')
            self.assertEqual(res['data']['is_staff'], False)

            # change second object
            just_object.email = '*****@*****.**'
            just_object.save()

            # check that nothing happened
            self.assertIsNone(client.receive())

            # delete
            sub_object.delete()
            just_object.delete()
            res = json.loads(client.receive()['text'])
            self.assertEqual(res['action'], 'deleted')
            self.assertEqual(res['data']['username'], 'sub_object')
            self.assertEqual(res['data']['email'], '*****@*****.**')
            self.assertEqual(res['data']['is_staff'], False)
Exemplo n.º 44
0
    def test_demultiplexer_with_wrong_payload(self):
        class Demultiplexer(WebsocketDemultiplexer):
            mapping = {
                'users': 'binding.users',
            }

            groups = ['inbound']

        with apply_routes([Demultiplexer.as_route(path='/')]):
            client = HttpClient()
            client.send_and_consume('websocket.connect', path='/')

            with self.assertRaises(ValueError) as value_error:
                client.send_and_consume('websocket.receive', path='/', text={
                    'stream': 'users', 'payload': 'test',
                })

            self.assertEqual(value_error.exception.args[0], 'Multiplexed frame payload is not a dict')

            message = client.get_next_message('binding.users')
            self.assertIsNone(message)
Exemplo n.º 45
0
    def test_demultiplexer_without_payload_and_steam(self):
        class Demultiplexer(WebsocketDemultiplexer):
            mapping = {
                'users': 'binding.users',
            }

            groups = ['inbound']

        with apply_routes([Demultiplexer.as_route(path='/')]):
            client = HttpClient()
            client.send_and_consume('websocket.connect', path='/')

            with self.assertRaises(ValueError) as value_error:
                client.send_and_consume('websocket.receive', path='/', text={
                    'nostream': 'users', 'payload': 'test',
                })

            self.assertIn('no channel/payload key', value_error.exception.args[0])

            message = client.get_next_message('binding.users')
            self.assertIsNone(message)

            with self.assertRaises(ValueError) as value_error:
                client.send_and_consume('websocket.receive', path='/', text={
                    'stream': 'users',
                })

            self.assertIn('no channel/payload key', value_error.exception.args[0])

            message = client.get_next_message('binding.users')
            self.assertIsNone(message)
Exemplo n.º 46
0
    def test_demultiplexer(self):
        class Demultiplexer(WebsocketDemultiplexer):
            mapping = {
                'users': 'binding.users',
            }

            groups = ['inbound']

        with apply_routes([Demultiplexer.as_route(path='/')]):
            client = HttpClient()
            client.send_and_consume('websocket.connect', path='/')

            # assert in group
            Group('inbound').send({'text': json.dumps({'test': 'yes'})}, immediately=True)
            self.assertEqual(client.receive(), {'test': 'yes'})

            # assert that demultiplexer stream message
            client.send_and_consume('websocket.receive', path='/',
                                    text={'stream': 'users', 'payload': {'test': 'yes'}})
            message = client.get_next_message('binding.users')
            self.assertIsNotNone(message)
            self.assertEqual(message.content['test'], 'yes')
Exemplo n.º 47
0
    def test_websocket_demultiplexer_send(self):

        class MyWebsocketConsumer(websockets.JsonWebsocketConsumer):
            def receive(self, content, multiplexer=None, **kwargs):
                self.send(content)

        class Demultiplexer(websockets.WebsocketDemultiplexer):

            consumers = {
                "mystream": MyWebsocketConsumer
            }

        with apply_routes([route_class(Demultiplexer, path='/path/(?P<id>\d+)')]):
            client = HttpClient()

            with self.assertRaises(SendNotAvailableOnDemultiplexer):
                client.send_and_consume('websocket.receive', path='/path/1', text={
                    "stream": "mystream",
                    "payload": {"text_field": "mytext"},
                })

                client.receive()
Exemplo n.º 48
0
    def test_inbound_create(self):
        self.assertEqual(User.objects.all().count(), 0)

        class Demultiplexer(WebsocketDemultiplexer):
            mapping = {
                'users': 'binding.users',
            }

            groups = ['inbound']

        class UserBinding(WebsocketBinding):
            model = User
            stream = 'users'
            fields = ['username', 'email', 'password', 'last_name']

            @classmethod
            def group_names(cls, instance, action):
                return ['users_outbound']

            def has_permission(self, user, action, pk):
                return True

        with apply_routes([Demultiplexer.as_route(path='/'), route('binding.users', UserBinding.consumer)]):
            client = HttpClient()
            client.send_and_consume('websocket.connect', path='/')
            client.send_and_consume('websocket.receive', path='/', text={
                'stream': 'users',
                'payload': {'action': CREATE, 'data': {'username': '******', 'email': 'test@user_steam.com'}}
            })
            # our Demultiplexer route message to the inbound consumer, so call Demultiplexer consumer
            client.consume('binding.users')

        self.assertEqual(User.objects.all().count(), 1)
        user = User.objects.all().first()
        self.assertEqual(user.username, 'test_inbound')
        self.assertEqual(user.email, 'test@user_steam.com')

        self.assertIsNone(client.receive())
Exemplo n.º 49
0
    def test_object_sub_with_subs_first(self):
        # define consumers
        routes = ObjectSubscribeConsumers.as_routes(path='/(?P<pk>\d+)/?', model=User)
        # create client
        client = HttpClient()
        with apply_routes([routes]):
            # subscribe for object changes
            client.send_and_consume(u'websocket.connect', content={'path': '/{}'.format('1')})

            # create object
            User.objects.create_user(username='******', email='*****@*****.**')
            res = json.loads(client.receive()['text'])
            self.assertTrue('data' in res.keys())
            self.assertTrue('action' in res.keys())
            self.assertTrue(res['action'] == 'created')
            data = res['data']
            self.assertEqual(data['username'], 'test')
            self.assertEqual(data['is_active'], True)
            self.assertEqual(data['email'], '*****@*****.**')
            self.assertEqual(data['is_staff'], False)

            # check that nothing happened
            self.assertIsNone(client.receive())
Exemplo n.º 50
0
    def test_dynamic_channels_names(self):

        class Test(Consumers):

            channel_name = 'test1'

            @consumer
            def test(self, message):
                return self.channel_name

        test = Test.as_routes()
        test_2 = Test.as_routes(channel_name='test')
        client = HttpClient()

        with apply_routes([test]):
            client.send_and_consume(u'websocket.receive')

        with apply_routes([test_2]):
            client.send_and_consume(u'websocket.receive')
        channel_layer = channel_layers[DEFAULT_CHANNEL_LAYER]

        self.assertEqual(len(channel_layer._channels), 3, channel_layer._channels.keys())
        self.assertIn('test', channel_layer._channels.keys())
Exemplo n.º 51
0
    def test_inbound_update(self):
        user = User.objects.create(username='******', email='*****@*****.**')

        class Demultiplexer(WebsocketDemultiplexer):
            mapping = {
                'users': 'binding.users',
            }

            groups = ['inbound']

        class UserBinding(WebsocketBinding):
            model = User
            stream = 'users'
            fields = ['username', ]

            @classmethod
            def group_names(cls, instance, action):
                return ['users_outbound']

            def has_permission(self, user, action, pk):
                return True

        with apply_routes([Demultiplexer.as_route(path='/'), route('binding.users', UserBinding.consumer)]):
            client = HttpClient()
            client.send_and_consume('websocket.connect', path='/')
            client.send_and_consume('websocket.receive', path='/', text={
                'stream': 'users',
                'payload': {'action': UPDATE, 'pk': user.pk, 'data': {'username': '******'}}
            })
            # our Demultiplexer route message to the inbound consumer, so call Demultiplexer consumer
            client.consume('binding.users')

            user = User.objects.get(pk=user.pk)
            self.assertEqual(user.username, 'test_inbound')
            self.assertEqual(user.email, '*****@*****.**')

            # trying change field that not in binding fields
            client.send_and_consume('websocket.receive', path='/', text={
                'stream': 'users',
                'payload': {'action': UPDATE, 'pk': user.pk, 'data': {'email': '*****@*****.**'}}
            })
            client.consume('binding.users')

            user = User.objects.get(pk=user.pk)
            self.assertEqual(user.username, 'test_inbound')
            self.assertEqual(user.email, '*****@*****.**')
Exemplo n.º 52
0
    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+)')]):
            client = HttpClient()

            client.send_and_consume('websocket.connect', path='/path/1')
            self.assertEqual(client.receive(), {
                "stream": "mystream",
                "payload": {"id": "1"},
            })

            client.send_and_consume('websocket.receive', text={
                "stream": "mystream",
                "payload": {"text_field": "mytext"},
            }, path='/path/1')
            self.assertEqual(client.receive(), {
                "stream": "mystream",
                "payload": {"text_field": "mytext"},
            })

            client.send_and_consume('websocket.disconnect', path='/path/1')
            self.assertEqual(client.receive(), {
                "stream": "mystream",
                "payload": {"id": "1"},
            })
Exemplo n.º 53
0
    def test_crud_consumers(self):
        # create object
        for i in range(20):
            User.objects.create_user(username='******' + str(i), email='*****@*****.**')
        # create client
        client = HttpClient()

        with apply_routes([CRUDConsumers.as_routes(model=User, path='/', channel_name='test', paginate_by=10)]):
            client.send_and_consume(u'websocket.connect', {'path': '/'})
            client.send_and_consume(u'websocket.receive', {'path': '/', 'action': 'list', 'page': 2})
            client.consume('test')
            rec = client.receive()
            res = json.loads(json.loads(rec['text'])['response'])

            self.assertEqual(len(res), 10)
            self.assertEqual(res[0]['username'], 'test10')
            self.assertEqual(res[0]['email'], '*****@*****.**')
            self.assertEqual(res[0]['is_active'], True)

            client.send_and_consume(u'websocket.connect', {'path': '/{}'.format(10)})
            client.send_and_consume(u'websocket.receive', {'path': '/{}'.format(10), 'action': 'delete'})
            client.consume('test')

            self.assertFalse(User.objects.filter(pk=10).exists())

            data = {'username': '******'}
            client.send_and_consume('websocket.connect', {'path': '/{}'.format(11)})
            client.send_and_consume('websocket.receive', {'path': '/{}'.format(11), 'action': 'update',
                                                          'data': json.dumps(data)})
            client.consume('test')

            user = User.objects.filter(pk=11).first()
            self.assertTrue(user)
            self.assertEqual(user.username, 'new_name')