async def test_cog_app_command_error_from_command_with_error_handler( self, mock_bot: commands.Bot, mock_interaction: discord.Interaction, ) -> None: on_error = AsyncMock() on_command_error = AsyncMock() error = app_commands.CheckFailure() class MyCog(commands.GroupCog): @app_commands.command() async def my_command(self, interaction: discord.Interaction) -> None: ... @my_command.error async def on_my_command_with_handler_error( self, interaction: discord.Interaction, error: app_commands.AppCommandError, ) -> None: await on_command_error(self, interaction, error) def cog_app_command_error( self, interaction: discord.Interaction, error: app_commands.AppCommandError, ) -> Coroutine[Any, Any, None]: return on_error(self, interaction, error) cog = MyCog(mock_bot) await cog.my_command._invoke_error_handlers(mock_interaction, error) on_command_error.assert_awaited_once_with(cog, mock_interaction, error) on_error.assert_awaited_once_with(cog, mock_interaction, error)
async def test_direct_dispatch_on_known_trigger( self, dispatch_mock: AsyncMock) -> None: sample: SampleMachine = SampleMachine() await sample.trigger("trigger1") dispatch_mock.assert_awaited_once_with("trigger1")
async def test_cog_app_command_error_from_sub_group_with_handler( self, mock_bot: commands.Bot, mock_interaction: discord.Interaction, mock_on_sub_group_error_handler: AsyncMock, sub_group_with_handler_class: Type[app_commands.Group], ) -> None: on_error = AsyncMock() error = app_commands.CheckFailure() class MyCog(commands.GroupCog): my_sub_group = sub_group_with_handler_class() def cog_app_command_error( self, interaction: discord.Interaction, error: app_commands.AppCommandError, ) -> Coroutine[Any, Any, None]: return on_error(self, interaction, error) cog = MyCog(mock_bot) await cog.my_sub_group.my_sub_group_command._invoke_error_handlers( mock_interaction, error) # type: ignore mock_on_sub_group_error_handler.assert_awaited_once_with( cog.my_sub_group, mock_interaction, error) on_error.assert_awaited_once_with(cog, mock_interaction, error)
async def test_deny_request(monkeypatch) -> None: mock_process = AsyncMock(name='_process_request') monkeypatch.setattr(bl, '_process_request', mock_process) request_id = '123' history = 'history' await bl.deny_request(history, request_id) mock_process.assert_awaited_once_with(history, request_id, 'denied')
async def was_license_set(mock_obj: mock.AsyncMock, core, namespace, master_node_pod, has_ssl, license): try: mock_obj.assert_awaited_once_with(core, namespace, master_node_pod, has_ssl, license, mock.ANY) except AssertionError: return False else: return True
def test_register_module(test_client: Session, app: FastAPI, module: Module, monkeypatch) -> None: mock = AsyncMock(name='add_or_replace_module') monkeypatch.setattr(app.state.storage, 'add_or_replace_module', mock) resp = test_client.post('/api/modules/', json=module.dict()) assert resp.status_code == 200 assert resp.json() == module.dict() mock.assert_awaited_once_with(module)
def test_get_module_by_name(test_client: Session, app: FastAPI, module: Module, monkeypatch) -> None: mock = AsyncMock(name='get_module', return_value=module) monkeypatch.setattr(app.state.storage, 'get_module', mock) resp = test_client.get('/api/modules/help') assert resp.status_code == 200 assert resp.json() == module.dict() mock.assert_awaited_once_with(module.name)
async def test_transition_by_trigger(self, after_mock: AsyncMock) -> None: sample: SampleMachine = SampleMachine() await sample.run() await sample.trigger("trigger1", magic="black") await sample.done() self.assertEqual(sample.current, "state2") after_mock.assert_awaited_once_with(sample._flux._store, {"magic": "black"})
async def test_action_dispatcher_dispatch_views( action_dispatcher: ActionDispatcher, test_view_payload: Dict, monkeypatch) -> None: mock = AsyncMock() monkeypatch.setattr(action_dispatcher, '_trigger_all_actions', mock) await action_dispatcher.dispatch(test_view_payload) mock.assert_awaited_once_with({'view_submission:callback_id'}, test_view_payload)
async def test_command_dispatcher_dispatch( command_dispatcher: CommandDispatcher, module: Module, test_command_payload: Callable, monkeypatch) -> None: mock = AsyncMock() monkeypatch.setattr(command_dispatcher, '_trigger_command', mock) command_dispatcher.storage.get_module.return_value = module payload = test_command_payload('help me 123') await command_dispatcher.dispatch(payload) mock.assert_awaited_once_with(module, module.commands['me'], ['123'], payload)
async def test_execute_command_async(module: Module) -> None: name = 'test' mock = AsyncMock(name='func') @module.command(name) async def func(arg: str) -> None: pass module._commands[name].func = mock # noqa await module.execute_command(name, {'arg': 'test'}) mock.assert_awaited_once_with(arg='test')
def test_get_all_modules(test_client: Session, app: FastAPI, module: Module, monkeypatch) -> None: mock = AsyncMock(name='get_all_modules', return_value={module.name: module}) monkeypatch.setattr(app.state.storage, 'get_all_modules', mock) resp = test_client.get('/api/modules/') assert resp.status_code == 200 assert resp.json() == {'modules': {module.name: module.dict()}} mock.assert_awaited_once_with()
def test_fire_registered_event_cancel(self): bot = Bot("app_name", "version") bot.guild_logs_file = self.LOG_PATH on_guild_remove = AsyncMock() on_guild_remove.__name__ = "on_guild_remove" on_guild_remove.return_value = False bot.register_event(on_guild_remove) guild = AsyncMock() self._await(bot.on_guild_remove(guild)) on_guild_remove.assert_awaited_once_with(guild) self.assertFalse(path.exists(self.LOG_PATH))
def test_fire_registered_event(self): bot = Bot("app_name", "version") bot.guild_logs_file = self.LOG_PATH on_guild_join = AsyncMock() on_guild_join.__name__ = "on_guild_join" on_guild_join.return_value = True bot.register_event(on_guild_join) guild = AsyncMock() self._await(bot.on_guild_join(guild)) on_guild_join.assert_awaited_once_with(guild) self.assertTrue(path.exists(self.LOG_PATH))
def test_fire_registered_event_cancel(self): bot = Bot("app_name", "version") on_message = AsyncMock() on_message.__name__ = "on_message" on_message.return_value = False bot.register_event(on_message) watcher_callback = AsyncMock() bot.register_watcher(watcher_callback) message = AsyncMock() message.content = "hello there" self._await(bot.on_message(message)) on_message.assert_awaited_once_with(message) watcher_callback.assert_not_awaited()
async def test_async_slack_request(set_current_module: Module, monkeypatch) -> None: mock_api = AsyncMock(name='request_api_slack_post') monkeypatch.setattr(AsyncMetabotApi, 'request_api_slack_post', mock_api) method = 'chat_postMessage' payload = {'text': 'test', 'channel': '#general'} await async_slack_request(method, payload) mock_api.assert_awaited_once_with( SlackRequest( method=method, payload=payload, ))
async def test_add_x_trace_id_no_trace_id_set_args_length_too_short(): args = ["a", 2, "b", 3] func_return_value = "value" func = AsyncMock() func.return_value = func_return_value actual_return_value = await add_x_trace_id(func)(*deepcopy(args)) assert DistributedTracingContext.has_trace_id() assert len(DistributedTracingContext.get_trace_id()) == TRACE_ID_LENGTH assert actual_return_value == func_return_value func.assert_awaited_once_with(*args)
def test_no_mention(self): bot = Bot("app_name", "version") bot.enforce_write_permission = False simple_callback = AsyncMock() bot.register_command("test", simple_callback, "short", "long") watcher_callback = AsyncMock() bot.register_watcher(watcher_callback) fallback_callback = AsyncMock() bot.register_fallback(fallback_callback) message = AsyncMock() message.content = "hello there" self._await(bot.on_message(message)) simple_callback.assert_not_awaited() watcher_callback.assert_awaited_once_with(bot.client, message) fallback_callback.assert_not_awaited()
async def test_add_x_trace_id_trace_id_set_args_length_too_short(): args = ["a", 2, "b", 3] func_return_value = "value" trace_id = "trace-id" func = AsyncMock() func.return_value = func_return_value DistributedTracingContext.set_trace_id(trace_id) actual_return_value = await add_x_trace_id(func)(*deepcopy(args)) assert DistributedTracingContext.get_trace_id() == trace_id assert actual_return_value == func_return_value func.assert_awaited_once_with(*args)
def test_mention_command_regex(self): bot = Bot("app_name", "version") bot.enforce_write_permission = False bot.client.user.id = "12345" regex_callback = AsyncMock() bot.register_command("^t[eo]a?st$", regex_callback, "short", "long") watcher_callback = AsyncMock() bot.register_watcher(watcher_callback) fallback_callback = AsyncMock() bot.register_fallback(fallback_callback) message = AsyncMock() message.content = "<@12345> toast hey" self._await(bot.on_message(message)) regex_callback.assert_awaited_once_with(bot.client, message, "toast", "hey") watcher_callback.assert_awaited_once_with(bot.client, message) fallback_callback.assert_not_awaited()
async def test_approve_request(monkeypatch, test_request: Dict) -> None: mock_process = AsyncMock(name='_process_request') mock_process.return_value = test_request monkeypatch.setattr(bl, '_process_request', mock_process) mock_increase = AsyncMock(name='increase_days_by_user') monkeypatch.setattr(bl, 'increase_days_by_user', mock_increase) request_id = '123' users = 'users' history = 'history' await bl.approve_request(history, users, request_id) mock_process.assert_awaited_once_with(history, request_id, 'approved') mock_increase.assert_awaited_once_with(users, test_request['leave_type'], Decimal(-test_request['duration']), test_request['user_id'])
def test_mention_command_simple(self): bot = Bot("app_name", "version") bot.enforce_write_permission = False bot.client.user.id = "12345" simple_callback = AsyncMock() bot.register_command("test", simple_callback, "short", "long") watcher_callback = AsyncMock() bot.register_watcher(watcher_callback) fallback_callback = AsyncMock() bot.register_fallback(fallback_callback) message = AsyncMock() message.content = "<@12345> test arg0 arg1" self._await(bot.on_message(message)) simple_callback.assert_awaited_once_with(bot.client, message, "test", "arg0", "arg1") watcher_callback.assert_awaited_once_with(bot.client, message) fallback_callback.assert_not_awaited()
def test_membership_cmd(dry_run, confirmation, exit_code, monkeypatch): # Monkeypatch and Mock monkeypatch.setattr(auth, "auth_method", patched_auth_method) monkeypatch.setattr(HeadBlock, "get_head", patched.head_block) monkeypatch.setattr(wot, "choose_identity", patched_choose_identity) patched_display_confirmation_table = AsyncMock() monkeypatch.setattr( membership, "display_confirmation_table", patched_display_confirmation_table, ) if not dry_run: patched_generate_membership_document = Mock() monkeypatch.setattr( membership, "generate_membership_document", patched_generate_membership_document, ) # Run membership command command = ["membership"] if dry_run: command += ["--dry-run"] confirmations = "No\nYes\nYes" if confirmation else "No\nYes\nNo" result = CliRunner().invoke(cli, args=command, input=confirmations) # Assert functions are called patched_display_confirmation_table.assert_awaited_once_with( identity_uid, pubkey, identity_timestamp, ) if not dry_run and confirmation: patched_generate_membership_document.assert_called_with( currency, pubkey, membership_timestamp, identity_uid, identity_timestamp, ) if dry_run: assert "Type: Membership" in result.output assert result.exit_code == exit_code
def test_any_mention_off(self): bot = Bot("app_name", "version") bot.enforce_write_permission = False bot.any_mention = False bot.client.user.id = "12345" simple_callback = AsyncMock() bot.register_command("test", simple_callback, "short", "long") watcher_callback = AsyncMock() bot.register_watcher(watcher_callback) fallback_callback = AsyncMock() bot.register_fallback(fallback_callback) message = AsyncMock() message.content = "test <@12345> arg0 arg1" message.channel.type == discord.ChannelType.private message.mentions = [bot.client.user] self._await(bot.on_message(message)) simple_callback.assert_not_awaited() watcher_callback.assert_awaited_once_with(bot.client, message) fallback_callback.assert_not_awaited()
async def test_open_request_view(test_command_metadata: Dict, monkeypatch) -> None: mock_get_days = AsyncMock(name='get_days_by_user_id') monkeypatch.setattr(bl, 'get_days_by_user_id', mock_get_days) mock_builder = MagicMock(name='build_request_view') view = mock_builder.return_value = {} monkeypatch.setattr(bl, 'build_request_view', mock_builder) mock_slack = AsyncMock(name='async_slack_request') monkeypatch.setattr(bl, 'async_slack_request', mock_slack) await bl.open_request_view(None) mock_slack.assert_awaited_once_with( method='views_open', payload={ 'trigger_id': test_command_metadata['trigger_id'], 'view': view })
async def test_notify_admins(monkeypatch, test_command_metadata: Dict) -> None: mock_builder = MagicMock(name='build_admin_request_notification') blocks = mock_builder.return_value = [{ 'type': 'section', 'text': { 'type': 'mrkdwn', 'text': 'some text' } }] monkeypatch.setattr(bl, 'build_admin_request_notification', mock_builder) mock_notification = AsyncMock(name='build_admin_request_notification') monkeypatch.setattr(bl, '_send_notification', mock_notification) await bl._notify_admins('vacation', date.today(), date.today(), 1, 10, 'reason', 'asdasdasd') mock_builder.assert_called_once() mock_notification.assert_awaited_once_with(blocks[0]['text']['text'], blocks, bl.ADMIN_CHANNEL)
async def test_send_passage( mocker: pytest_mock.MockerFixture, mock_send_embed: AsyncMock, passage: Passage, kwargs: dict[str, Any], description: str, footer: str, ephemeral: Any, ) -> None: result = await utils.send_passage(mocker.sentinel.ctx_or_intx, passage, **kwargs) assert result is mocker.sentinel.send_embed_return mock_send_embed.assert_awaited_once_with( mocker.sentinel.ctx_or_intx, description=description, footer={'text': footer}, ephemeral=ephemeral, )
async def test_successful_login_with_session_id(delete_session: AsyncMock, users: ListDictStrAny, client: AsyncClient) -> None: ''' A user log in with an existing session_id which can be from the same user or not ''' session_id = 'abcd1234' cookies = {'session_id': session_id} email = users[0]['email'] password = users[0]['password'] resp = await client.post('/login', json={ 'email': email, 'password': password }, cookies=cookies) assert resp.status_code == 200 assert resp.cookies['session_id'] != session_id assert resp.cookies['csrf'] delete_session.assert_awaited_once_with(session_id)
async def test_consume_event_service(service_payload): mocked_query_json = AsyncMock() mocked_service_inspect = AsyncMock(return_value=service_payload) mocked_services_api = MagicMock() mocked_services_api.inspect = mocked_service_inspect mocked_docker = MagicMock() mocked_docker._query_json = mocked_query_json mocked_docker.services = mocked_services_api dummy_event = { "Type": "service", "Action": "create", "Actor": { "ID": service_payload["ID"], }, } def dummy_condition(service_spec): """Check if service name starts with `dummy-`.""" return not service_spec["Name"].startswith("dummy-") async def dummy_callback(service_spec): """Prepend service name with `dummy-`.""" service_spec["Name"] = f"dummy-{service_spec['Name']}" return service_spec consumer.register_rule("service", dummy_condition, dummy_callback) await consumer.consume_event(mocked_docker, dummy_event) update_payload = service.extract_update_payload(service_payload) data = await dummy_callback(update_payload) params = service.extract_update_params(service_payload) mocked_query_json.assert_awaited_once_with( f"services/{service_payload['ID']}/update", method="POST", data=json.dumps(data), params=params, )
async def test_authenticate(monkeypatch): import tome.middleware.auth fake_app = AsyncMock() fake_validate_api_key = AsyncMock() fake_validate_auth_token = AsyncMock() middleware = tome.middleware.auth.AuthenticationMiddleware(fake_app) monkeypatch.setattr(tome.middleware.auth.auth, "validate_api_key", fake_validate_api_key) monkeypatch.setattr(tome.middleware.auth.auth, "validate_auth_token", fake_validate_auth_token) fake_request = type("", (), {})() fake_request.headers = MutableHeaders({}) assert await middleware.authenticate(fake_request) == (None, ["anonymous"]) fake_request.headers["authorization"] = "fake" assert await middleware.authenticate(fake_request) == (None, ["anonymous"]) key = uuid.uuid4() fake_request.headers["authorization"] = "Bearer api-key-" + key.hex await middleware.authenticate(fake_request) fake_validate_api_key.assert_awaited_once_with(key) fake_validate_auth_token.assert_not_awaited() with pytest.raises(HTTPException) as exc_info: fake_request.headers["authorization"] = "Bearer api-key-invalid" await middleware.authenticate(fake_request) assert exc_info.value.status_code == 401 fake_validate_api_key.reset_mock() fake_validate_auth_token.reset_mock() fake_request.headers["authorization"] = "Bearer foobar-auth-token" await middleware.authenticate(fake_request) fake_validate_api_key.assert_not_awaited() fake_validate_auth_token.assert_awaited_once_with(b"foobar-auth-token")