"""Tests for PushClient""" from collections import defaultdict import exponent_server_sdk as expo from send_push_notifications.logger import get_logger from send_push_notifications.push_client import PushClient from tests.factories import UserDeviceFactory def test_push_client_send(db_session, mocker): logger = get_logger('test') provider = expo.PushClient() user_device = UserDeviceFactory.create() message = expo.PushMessage( to=f'ExponentPushToken {user_device.token}', body='Hello world', title='Title', data={} ) invalid_message = expo.PushMessage( to=f'ExponentPush', body='Hello world', title='Title', data={} ) mocker.patch.object(provider, 'publish_multiple') provider.publish_multiple.return_value = [ expo.PushResponse( push_message=message, status='ok', message='', details={} ) ] client = PushClient(provider=provider, logger=logger) client.send([message, invalid_message]) provider.publish_multiple.assert_called_with([message]) def test_push_client_send_for_multiple_projects(db_session, mocker): logger = get_logger('test') provider = expo.PushClient() chunk_size = 4 ratio = chunk_size // 2 # number of project 0 tokens // number of project 0 + project 1 tokens tokens = [f'ExponentPushToken {UserDeviceFactory.create().token}' for i in range(chunk_size)] messages = [expo.PushMessage( to=token, body='Hello world', title='Title', data={} ) for token in tokens] token_to_project = {token: int(i < ratio) for i, token in enumerate(tokens)} def expo_response(_messages): project_to_tokens = defaultdict(list) for _m in _messages: project_to_tokens[token_to_project[_m.to]].append(_m.to) if len(project_to_tokens) > 1: errors = [{ 'code': 'PUSH_TOO_MANY_EXPERIENCE_IDS', 'message': 'All push notification messages in the same request must be for the same project; ' 'check the details field to investigate conflicting tokens.', 'details': project_to_tokens, 'isTransient': False}] raise expo.PushServerError( message="Request failed", response="", errors=errors, response_data={'errors': errors} ) return [expo.PushResponse( push_message=m, status='ok', message='', details={} ) for m in _messages] mocker.patch.object(provider, 'publish_multiple', side_effect=expo_response) client = PushClient(provider=provider, logger=logger) receipts = client.send(messages) assert len(receipts) == len(messages) assert set([id(r.push_message) for r in receipts]) == set([id(m) for m in messages]) assert provider.publish_multiple.call_count == 3