async def test_dispatch_message_task_error(route): exc = Exception() route.deliver = AsyncMock(side_effect=exc) route.error_handler = AsyncMock(return_value="confirmation") dispatcher = LoaferDispatcher([route]) message = "message" confirmation = await dispatcher.dispatch_message(message, route) assert confirmation == "confirmation" assert route.deliver.called is True route.deliver.assert_called_once_with(message) assert route.error_handler.called is True
def client(client_class): client = AsyncMock() client_class.return_value = client if sys.version_info[:2] < (3, 8): client.read_gatt_char = CoroutineMock() client.write_gatt_char = CoroutineMock() connected = False async def is_connected(): nonlocal connected return connected async def connect(): nonlocal connected connected = True async def disconnect(): nonlocal connected connected = False client.is_connected.side_effect = is_connected client.connect.side_effect = connect client.disconnect.side_effect = disconnect yield client
async def test_dispatch_invalid_message(route, message): route.deliver = AsyncMock() dispatcher = LoaferDispatcher([route]) confirmation = await dispatcher.dispatch_message(message, route) assert confirmation is False assert route.deliver.called is False
async def test_receive_with_timeout(self): message = Message(MessageType.WEBSOCKET_INACTIVE) data = message.to_json() websocket = AsyncMock() websocket.recv = CoroutineMock() websocket.recv.return_value = data assert await receive(websocket, timeout_sec=3) == message
async def test_deliver_with_coroutine(dummy_provider): mock_handler = AsyncMock(return_value=False) route = Route(dummy_provider, mock_handler) message = "test" result = await route.deliver(message) assert result is False assert mock_handler.called assert message in mock_handler.call_args[0]
def route(provider): message_translator = Mock(translate=Mock( return_value={'content': 'message'})) route = AsyncMock(provider=provider, handler=Mock(), message_translator=message_translator, spec=Route) return route
async def test_dispatch_providers(route, event_loop): dispatcher = LoaferDispatcher([route]) dispatcher._dispatch_tasks = AsyncMock() dispatcher.stop_providers = Mock() await dispatcher.dispatch_providers(forever=False) assert dispatcher._dispatch_tasks.called dispatcher._dispatch_tasks.assert_called_once_with()
async def test_dispatch_without_tasks(route, event_loop): route.provider.fetch_messages = AsyncMock(return_value=[]) dispatcher = LoaferDispatcher([route]) await dispatcher._dispatch_tasks() assert route.provider.fetch_messages.called assert route.provider.confirm_message.called is False assert route.provider.message_not_processed.called is False
async def test_error_handler_coroutine(dummy_provider): error_handler = AsyncMock(return_value=True) route = Route(dummy_provider, mock.Mock(), error_handler=error_handler) exc = TypeError() exc_info = (type(exc), exc, "traceback") result = await route.error_handler(exc_info, "whatever") assert result is True assert error_handler.called error_handler.assert_called_once_with(exc_info, "whatever")
async def test_handle_exception_value_error(self, send, close): exception = ValueError("Hello!") websocket = AsyncMock() context = RequestFailedContext(FailureReason.INVALID_REQUEST, "Hello!") message = Message(MessageType.REQUEST_FAILED, context=context) json = message.to_json() await _handle_exception(exception, websocket) send.assert_awaited_once_with(websocket, json) close.assert_not_awaited()
async def test_schedule_obsolete_game_check(self, periodic, config): p = AsyncMock() p.start = CoroutineMock() periodic.return_value = p config.return_value = MagicMock(obsolete_game_check_period_sec=1, obsolete_game_check_delay_sec=2) await _schedule_obsolete_game_check() p.start.assert_awaited_once_with(delay=2) periodic.assert_called_once_with(1, _execute_obsolete_game_check)
async def test_message_processing(route): dispatcher = LoaferDispatcher([route]) dispatcher.dispatch_message = AsyncMock() await dispatcher._process_message("message", route) assert dispatcher.dispatch_message.called dispatcher.dispatch_message.assert_called_once_with("message", route) assert route.provider.confirm_message.called assert route.provider.message_not_processed.called is False route.provider.confirm_message.assert_called_once_with("message")
async def test_handle_exception_processing_error_comment( self, send, close): exception = ProcessingError(FailureReason.INVALID_PLAYER, "comment") websocket = AsyncMock() context = RequestFailedContext(FailureReason.INVALID_PLAYER, "comment") message = Message(MessageType.REQUEST_FAILED, context=context) json = message.to_json() await _handle_exception(exception, websocket) send.assert_awaited_once_with(websocket, json) close.assert_not_awaited()
async def test_dispatch_message_task_cancel(route): route.deliver = AsyncMock(side_effect=asyncio.CancelledError) dispatcher = LoaferDispatcher([route]) message = "message" confirmation = await dispatcher.dispatch_message(message, route) assert confirmation is False assert route.deliver.called route.deliver.assert_called_once_with(message)
async def test_dispatch_message_task_delete_message(route): route.deliver = AsyncMock(side_effect=DeleteMessage) dispatcher = LoaferDispatcher([route]) message = "rejected-message" confirmation = await dispatcher.dispatch_message(message, route) assert confirmation is True assert route.deliver.called route.deliver.assert_called_once_with(message)
async def test_dispatch_message(route): route.deliver = AsyncMock(return_value="confirmation") dispatcher = LoaferDispatcher([route]) message = "foobar" confirmation = await dispatcher.dispatch_message(message, route) assert confirmation == "confirmation" assert route.deliver.called route.deliver.assert_called_once_with(message)
async def test_handle_connection(self, handle_data, handle_exception, handle_connect, handle_disconnect): data = b"test data" websocket = AsyncMock() websocket.__aiter__.return_value = [data] await _handle_connection(websocket, "path") # path is unused handle_data.assert_called_once_with(data, websocket) handle_connect.assert_called_once_with(websocket) handle_disconnect.assert_called_once_with(websocket) handle_exception.assert_not_called()
async def test_handle_exception_processing_error_websocket_limit( self, send, close): exception = ProcessingError(FailureReason.WEBSOCKET_LIMIT) websocket = AsyncMock() context = RequestFailedContext(FailureReason.WEBSOCKET_LIMIT, FailureReason.WEBSOCKET_LIMIT.value) message = Message(MessageType.REQUEST_FAILED, context=context) json = message.to_json() await _handle_exception(exception, websocket) send.assert_awaited_once_with(websocket, json) close.assert_awaited_once_with(websocket)
async def test_handle_disconnect(self, manager, event_handler): handler = mock_handler() manager.return_value = handler.manager event_handler.return_value = handler websocket = AsyncMock() await _handle_disconnect(websocket) event_handler.assert_called_once_with(manager.return_value) handler.manager.lock.assert_awaited() handler.handle_websocket_disconnected_event.assert_called_once_with( websocket) handler.execute_tasks.assert_awaited_once()
async def test_handle_exception_fail(self, send, close): # this just confirms that send failures aren't propogated to the caller (we intentionally ignore them) exception = ProcessingError(FailureReason.INVALID_PLAYER) websocket = AsyncMock() send.side_effect = Exception("Send failed!") context = RequestFailedContext(FailureReason.INVALID_PLAYER, FailureReason.INVALID_PLAYER.value) message = Message(MessageType.REQUEST_FAILED, context=context) json = message.to_json() await _handle_exception(exception, websocket) send.assert_awaited_once_with(websocket, json) close.assert_not_awaited()
async def test_deliver_with_message_translator(dummy_provider): mock_handler = AsyncMock(return_value=True) route = Route(dummy_provider, mock_handler) route.apply_message_translator = mock.Mock(return_value={ "content": "whatever", "metadata": {} }) result = await route.deliver("test") assert result is True assert route.apply_message_translator.called assert mock_handler.called mock_handler.assert_called_once_with("whatever", {})
async def test_handle_connection_shutdown(self, handle_data, handle_exception, handle_connect, handle_disconnect): websocket = AsyncMock() exception = ConnectionClosed(None, None) websocket.__aiter__.side_effect = exception # the wait on the websocket is what throws the connection closed handle_data.side_effect = exception await _handle_connection(websocket, "path") # path is unused handle_data.assert_not_called() handle_connect.assert_called_once_with(websocket) handle_disconnect.assert_called_once_with(websocket) handle_exception.assert_not_called()
async def test_handle_data(self, manager, event_handler, handle_message, data): handler = mock_handler() manager.return_value = handler.manager event_handler.return_value = handler websocket = AsyncMock() json = data["list.json"] message = Message.for_json(json) await _handle_data(json, websocket) event_handler.assert_called_once_with(manager.return_value) handler.manager.lock.assert_awaited() handle_message.assert_called_once_with(handler, message, websocket) handler.execute_tasks.assert_awaited_once()
async def test_handle_connection_exception(self, handle_data, handle_exception, handle_connect, handle_disconnect): data = b"test data" websocket = AsyncMock() websocket.__aiter__.return_value = [data] exception = ProcessingError(FailureReason.INTERNAL_ERROR) handle_data.side_effect = exception await _handle_connection(websocket, "path") # path is unused handle_data.assert_called_once_with(data, websocket) handle_connect.assert_called_once_with(websocket) handle_disconnect.assert_called_once_with(websocket) handle_exception.assert_called_once_with(exception, websocket)
def test_add_signal_handlers(self, signaler): stop = AsyncMock() set_result = AsyncMock() stop.set_result = set_result loop = AsyncMock() loop.create_future.return_value = stop assert _add_signal_handlers(loop) is stop if sys.platform == "win32": assert [signal.SIGTERM, signal.SIGINT ] == [c.args[0] for c in signaler.call_args_list ] # confirm all signals are handled signaler.call_args_list[0].args[1]( "x", "y" ) # execute the handler with dummy arguments (which are ignored) stop.set_result.assert_called_once_with( None ) # confirm that the handler sets the stop future result properly else: loop.add_signal_handler.assert_has_calls([ call(signal.SIGHUP, set_result, None), # pylint: disable=no-member call(signal.SIGTERM, set_result, None), call(signal.SIGINT, set_result, None), ])
def boto_client_sqs(queue_url, sqs_message): mock_client = mock.Mock() mock_client.get_queue_url = AsyncMock(return_value=queue_url) mock_client.delete_message = AsyncMock() mock_client.receive_message = AsyncMock(return_value=sqs_message) mock_client.send_message = AsyncMock(return_value=sqs_send_message) mock_client.change_message_visibility = AsyncMock() mock_client.close = AsyncMock() return mock_client
def test_run_server(self, websocket_server, config): # I'm not entirely sure I'm testing this properly. # I can't find a good way to prove that _websocket_server(stop) was passed to run_until_complete # But, the function is so short that I can eyeball it, and it will either work or it won't when run by hand config.return_value = MagicMock(server_host="host", server_port=1234, close_timeout_sec=8) stop = asyncio.Future() stop.set_result(None) loop = AsyncMock() _run_server(loop, stop) loop.run_until_complete.assert_called_once() websocket_server.assert_called_once_with(stop=stop, host="host", port=1234, close_timeout_sec=2) loop.stop.assert_called_once() loop.close.assert_called_once()
async def mocked_connect_robust(loop=None, host=None): conn_mock = AsyncMock(spec=aio_pika.robust_connection.RobustConnection) conn_mock.loop = loop conn_mock.is_closed = closed chan_mock = CoroutineMock() exchange_mock = CoroutineMock() queue_mock = CoroutineMock() queue_mock.bind = CoroutineMock() queue_mock.consume = CoroutineMock() exchange_mock.publish = CoroutineMock() chan_mock.declare_exchange = CoroutineMock(return_value=exchange_mock) chan_mock.declare_queue = CoroutineMock(return_value=queue_mock) conn_mock.close = CoroutineMock() conn_mock.channel = CoroutineMock(return_value=chan_mock) return conn_mock
def _session_app() -> Quart: app = Quart(__name__) app.session_interface = AsyncMock(spec=SessionInterface) app.session_interface.open_session.return_value = SecureCookieSession() # type: ignore app.session_interface.is_null_session.return_value = False # type: ignore @app.route("/") async def route() -> str: session["a"] = "b" return "" @app.websocket("/ws/") async def ws() -> None: session["a"] = "b" await websocket.accept() await websocket.send("") @app.websocket("/ws_return/") async def ws_return() -> str: session["a"] = "b" return "" return app
def boto_client_sns(sns_publish, sns_list_topics): mock_client = mock.Mock() mock_client.publish = AsyncMock(return_value=sns_publish) mock_client.close = AsyncMock() return mock_client