예제 #1
0
    def test_post_new_user(self, mock_send_notif):
        """Tests post request for request view for new user."""
        resp = self.client.post(
            '/request/' + self.loc_req.uuid,
            data=dict(lat='11', lng='22', message=u'Салют'))
        self.assertEqual(200, resp.status_code)
        notif = ndb_models.LocationNotification.get_by_session_token(
            self.loc_req.session.token)[0]
        data = json.loads(resp.content)
        notif_dict = notif.to_dict()
        notif_dict['created_date'] = data['created_date']
        self.assertTrue(notif.session.complete)
        self.assertEqual(notif_dict, data)
        self.assertEqual(u'Салют', data['message'])

        self.assertEqual(1, mock_send_notif.call_count)
        mock_send_notif.assert_called_with(
            'testuser', '*****@*****.**', 'notification', notif.id)

        task = self.taskq.get_filtered_tasks(queue_names='mail')[0]
        test_utils.execute_queue_task(self.api_client, task)
        messages = self.mail_stub.get_sent_messages()
        test_utils.verify_email(
            messages, 1, '*****@*****.**',
            [u'Салют', u'Hi, Test Юзер', '[email protected] sent a message',
             '.com/location/' + notif.uuid])
예제 #2
0
    def test_success_all_messages(self, urlopen_mock):
        """All messages are pushed successfully."""
        taskqueue.add(queue_name='push',
                      url='/tasks/push/gcm',
                      params=dict(recipient_username=self.user.username,
                                  message_type=api_args.NOTIFICATION,
                                  message_id=123))
        tasks = self.taskq.get_filtered_tasks(queue_names='push')
        results = [dict(message_id='0:22'), dict(message_id='0:33')]
        gcm_resp = _gcm_response(success=2, results=results)
        urlopen_mock.return_value = mock.Mock(read=mock.Mock(
            return_value=gcm_resp))
        resp = test_utils.execute_queue_task(self.client, tasks[0])

        # Test request
        req = urlopen_mock.call_args[0][0]
        self.assertEqual(1, urlopen_mock.call_count)
        self.assertEqual('https://android.googleapis.com/gcm/send',
                         req.get_full_url())
        expected_data = dict(data=dict(message='sent you a new location',
                                       title='Eucaby',
                                       type=api_args.NOTIFICATION,
                                       id=123),
                             registration_ids=['12', '23'])
        self.assertEqual(expected_data, json.loads(req.data))
        self.assertEqual(['Content-type', 'Authorization'], req.headers.keys())
        self.assertEqual('application/json', req.headers['Content-type'])

        # Nothing has changed in database
        self._assert_device_data([('12', True), ('23', True)])
        self.assertEqual(200, resp.status_code)
예제 #3
0
def _assert_error_cases(cases, taskq, client, queue_name, url):
    """Util to test general error cases."""
    kwargs = dict(queue_name=queue_name, url=url)
    for i, case in enumerate(cases):
        qkwargs = kwargs.copy()
        if case[0]:  # params parameter
            qkwargs['params'] = case[0]
        taskqueue.add(**qkwargs)
        tasks = taskq.get_filtered_tasks(queue_names=queue_name)
        assert i + 1 == len(tasks)
        resp = test_utils.execute_queue_task(client, tasks[i])
        # The failed task should not be retried so return 200 code
        assert 200 == resp.status_code
        assert case[1] in resp.data  # Assert data substring
예제 #4
0
    def test_send_notifications(self):
        """Tests send notifications."""
        # Send notification
        gae_utils.send_notification(self.user.username, u'Test Юзер',
                                    api_args.NOTIFICATION, 123)

        # Verify result
        tasks = self.taskq.get_filtered_tasks(queue_names='push')
        assert 2 == len(tasks)
        # Android task
        with mock.patch('eucaby_api.tasks.gcm.GCM.json_request') as req_mock:
            req_mock.return_value = {}
            resp_android = test_utils.execute_queue_task(self.client, tasks[0])

            # Test GCM request
            self.assertEqual(1, req_mock.call_count)
            req_mock.assert_called_with(registration_ids=['12'],
                                        data=self.payload_data,
                                        retries=7)
            self.assertEqual(200, resp_android.status_code)

        # iOS task
        with mock.patch('eucaby_api.tasks.api_utils.create_apns_socket'
                        ) as mock_create_socket:
            apns_socket = mock.Mock()
            mock_create_socket.return_value = apns_socket
            # Test APNs request
            # Note: We currently use send_notification for APNs. Fix test
            #       when using send_notification_multiple.
            #       See comments for the method.
            # mock_send_notif = (apns_socket.gateway_server.
            #                    send_notification_multiple)
            mock_send_notif = apns_socket.gateway_server.send_notification
            resp_ios = test_utils.execute_queue_task(self.client, tasks[1])
            self.assertEqual(1, mock_send_notif.call_count)
            self.assertEqual(200, resp_ios.status_code)
예제 #5
0
 def test_mail(self):
     """Tests sending email."""
     params = dict(subject='Some subject',
                   body=u'Текст сообщения',
                   recipient=['*****@*****.**', '*****@*****.**'])
     taskqueue.add(queue_name='mail', url='/tasks/mail', params=params)
     tasks = self.taskq.get_filtered_tasks(queue_names='mail')
     self.assertEqual(1, len(tasks))
     resp = test_utils.execute_queue_task(self.client, tasks[0])
     self.assertEqual(200, resp.status_code)
     messages = self.mail_stub.get_sent_messages()
     self.assertEqual(1, len(messages))
     message = messages[0]
     self.assertEqual(u'Текст сообщения', message.body.decode())
     self.assertEqual('Some subject', message.subject)
     self.assertEqual('[email protected], [email protected]', message.to)
예제 #6
0
 def test_invalid_registration(self, urlopen_mock, sleep_mock):  # pylint: disable=unused-argument
     """Tests InvalidRegistration error message."""
     taskqueue.add(queue_name='push',
                   url='/tasks/push/gcm',
                   params=dict(recipient_username=self.user.username,
                               message_type=api_args.NOTIFICATION,
                               message_id=123))
     tasks = self.taskq.get_filtered_tasks(queue_names='push')
     results = [dict(message_id='0:22'), dict(error='InvalidRegistration')]
     gcm_resp = _gcm_response(success=1, failure=1, results=results)
     urlopen_mock.return_value = mock.Mock(read=mock.Mock(
         return_value=gcm_resp))
     resp = test_utils.execute_queue_task(self.client, tasks[0])
     # Device '23' is deactivated
     self._assert_device_data([('12', True)])
     self.assertEqual(200, resp.status_code)
예제 #7
0
 def test_error_code(self, urlopen_mock):
     """Tests http error codes."""
     taskqueue.add(queue_name='push',
                   url='/tasks/push/gcm',
                   params=dict(recipient_username=self.user.username,
                               message_type=api_args.NOTIFICATION,
                               message_id=123))
     tasks = self.taskq.get_filtered_tasks(queue_names='push')
     cases = ((400, 'The request could not be parsed as JSON'),
              (401, 'There was an error authenticating the sender account'),
              (500, 'GCM service error: 500'),
              (503, 'GCM service is unavailable'))
     for case in cases:
         urlopen_mock.side_effect = urllib2.HTTPError(
             mock.Mock(), case[0], '', mock.Mock(), mock.Mock())
         resp = test_utils.execute_queue_task(self.client, tasks[0])
         self.assertEqual(500, resp.status_code)
         self.assertEqual(case[1], resp.data)
예제 #8
0
 def test_error_unavailable(self, urlopen_mock, sleep_mock):  # pylint: disable=unused-argument
     """Tests Unavailable error message."""
     # Mock time.sleep function so that you don't have to wait for retries
     taskqueue.add(queue_name='push',
                   url='/tasks/push/gcm',
                   params=dict(recipient_username=self.user.username,
                               message_type=api_args.NOTIFICATION,
                               message_id=123))
     tasks = self.taskq.get_filtered_tasks(queue_names='push')
     results = [dict(message_id='0:22'), dict(error='Unavailable')]
     gcm_resp = _gcm_response(success=1, failure=1, results=results)
     urlopen_mock.return_value = mock.Mock(read=mock.Mock(
         return_value=gcm_resp))
     resp = test_utils.execute_queue_task(self.client, tasks[0])
     # Trick to make 2 calls instead of 7 by clearing the first successful.
     self.assertEqual(2, urlopen_mock.call_count)
     # Nothing has changed in database Unavailable error doesn't modify
     self._assert_device_data([('12', True), ('23', True)])
     self.assertEqual(200, resp.status_code)
예제 #9
0
 def test_success_canonical_ids(self, urlopen_mock):
     """Response has canonical ids."""
     taskqueue.add(queue_name='push',
                   url='/tasks/push/gcm',
                   params=dict(recipient_username=self.user.username,
                               message_type=api_args.NOTIFICATION,
                               message_id=123))
     tasks = self.taskq.get_filtered_tasks(queue_names='push')
     # Newly created device
     models.Device.get_or_create(self.user, '44', api_args.ANDROID)
     results = [
         dict(message_id='0:22'),  # reg_id='44'
         dict(message_id='0:33', registration_id='44'),  # reg_id='12'
         dict(error='NotRegistered')
     ]  # reg_id='23'
     gcm_resp = _gcm_response(success=3, canonical_ids=1, results=results)
     urlopen_mock.return_value = mock.Mock(read=mock.Mock(
         return_value=gcm_resp))
     resp = test_utils.execute_queue_task(self.client, tasks[0])
     # Note: Devices with reg_id '12' and '23' got deactivated
     self._assert_device_data([('44', True)])
     self.assertEqual(200, resp.status_code)
예제 #10
0
    def test_success(self, mock_add_item, mock_payload, mock_create_socket):
        """Tests sending push notifications to iOS devices."""
        apns_socket = mock.Mock()
        mock_create_socket.return_value = apns_socket
        taskqueue.add(queue_name='push',
                      url='/tasks/push/apns',
                      params=dict(recipient_username=self.user.username,
                                  sender_name='Name',
                                  message_type=api_args.NOTIFICATION,
                                  message_id=123))
        tasks = self.taskq.get_filtered_tasks(queue_names='push')

        resp = test_utils.execute_queue_task(self.client, tasks[0])
        self.assertEqual(200, resp.status_code)

        mock_payload.assert_called_with(sound='default',
                                        alert='Name\nsent you a new location',
                                        custom=dict(type=api_args.NOTIFICATION,
                                                    id=123))
        # Note: Fix tests when using send_notification_multiple.
        mock_send_notif = apns_socket.gateway_server.send_notification
        self.assertEqual(0, mock_add_item.call_count)
        self.assertEqual(2, mock_send_notif.call_count)