def test_bot_mention_properly_processed_when_bot_found(self): client_id = 0 message = Message(message_id=0, sender_id=1, receiver_id=2, team_id=0, content="@test hola", send_type=SendMessageType.CHANNEL, message_type=MessageType.TEXT) '''Mocked outputs''' bot = Bot(bot_id=0, name="test", callback=None, token=None) def post(url, json, headers): from tests.test_services import test_bots MockedBotDatabase.posted_json = json sys.modules[ "daos.bots"].BotDatabaseClient.get_bot_by_id.return_value = bot sys.modules["requests"].post = MagicMock(side_effect=post) BotService.process_mention(client_id, message) self.assertIsNotNone(MockedBotDatabase.posted_json) self.assertEqual(1, MockedBotDatabase.posted_json.get("user_id")) self.assertEqual(2, MockedBotDatabase.posted_json.get("chat_id")) self.assertEqual(0, MockedBotDatabase.posted_json.get("team_id")) self.assertEqual("hola", MockedBotDatabase.posted_json.get("params"))
def accept_invite(cls, invitation_data): user = Authenticator.authenticate(invitation_data) invite = TeamDatabaseClient.get_team_invite_by_token( invitation_data.invite_token, user.email) if invite is None: return BadRequestTeamMessageResponse( "You weren't invited to this team.", UserResponseStatus.WRONG_CREDENTIALS.value) new_user_team = TeamUser(user_id=user.id, team_id=invite.team_id) try: TeamDatabaseClient.add_team_user(new_user_team) TeamDatabaseClient.delete_invite(invite) DatabaseClient.commit() BotService.tito_welcome(new_user_team.user_id, new_user_team.team_id) cls.logger().info( f"User #{user.id} joined team #{invite.team_id}.") except IntegrityError: DatabaseClient.rollback() cls.logger().error( f"User #{user.id} failed at joining team #{invite.team_id}.") return UnsuccessfulTeamMessageResponse("Couldn't join team.") else: return SuccessfulTeamMessageResponse( "Team joined!", TeamResponseStatus.ADDED.value)
def test_user_added_to_team_with_welcome_message_does_not_receives_titos_welcome( self): user_id = 1 team_id = 0 '''Mocked outputs''' tito = Bot(bot_id=0, name="tito", callback=None, token=None) team = Team(team_id=team_id, name="Test-Team", welcome_message="Helloooooou!") def post(url, json, headers): from tests.test_services import test_bots MockedBotDatabase.posted_json = json sys.modules[ "daos.bots"].BotDatabaseClient.get_bot_by_id.return_value = tito sys.modules[ "daos.teams"].TeamDatabaseClient.get_team_by_id.return_value = team sys.modules["requests"].post = MagicMock(side_effect=post) BotService.tito_welcome(user_id, team_id) self.assertIsNotNone(MockedBotDatabase.posted_json) self.assertEqual(0, MockedBotDatabase.posted_json.get("team_id")) self.assertEqual(1, MockedBotDatabase.posted_json.get("user_id")) self.assertEqual("welcome-user", MockedBotDatabase.posted_json.get("params")) self.assertEqual("Helloooooou!", MockedBotDatabase.posted_json.get("message"))
def save_mentions(cls, message, mentions): cls.logger().debug( f"Saving mentions from message #{message.message_id}.") try: for mention in mentions: if message.send_type == SendMessageType.CHANNEL.value: BotService.process_mention(mention, message) new_mention = Mention(message_id=message.message_id, client_id=mention) MessageDatabaseClient.add_mention(new_mention) cls.logger().debug(f"Mention saved for client {mention}.") NotificationService.notify_mention(message, mention) elif BotDatabaseClient.get_bot_by_id(mention) is None: new_mention = Mention(message_id=message.message_id, client_id=mention) MessageDatabaseClient.add_mention(new_mention) cls.logger().debug(f"Mention saved for user {mention}.") NotificationService.notify_mention(message, mention) DatabaseClient.commit() cls.logger().info( f"{len(mentions)} mentions saved for message #{message.message_id}." ) except IntegrityError: DatabaseClient.rollback() cls.logger().error( f"Couldn't save mentions for message #{message.message_id}.")
def add_user(cls, add_data): admin = Authenticator.authenticate(add_data.authentication, UserRoles.is_admin) user = UserDatabaseClient.get_user_by_id(add_data.add_user_id) if user is None: cls.logger().info(f"User {add_data.add_user_id} not found.") raise UserNotFoundError("User not found.", UserResponseStatus.USER_NOT_FOUND.value) if user.role == UserRoles.ADMIN.value: cls.logger().warning( f"Admin #{admin.id} trying to add other admin to a team.") return BadRequestTeamMessageResponse( "You cannot add an admin to a team!", TeamResponseStatus.ROLE_UNAVAILABLE.value) if TeamDatabaseClient.get_user_in_team_by_ids( user.id, add_data.authentication.team_id) is not None: cls.logger().info( f"User {add_data.add_user_id} already part of team #{add_data.authentication.team_id}." ) return BadRequestTeamMessageResponse( "This user already belongs to the team.", TeamResponseStatus.ALREADY_REGISTERED.value) previous_invitation = TeamDatabaseClient.get_team_invite( add_data.authentication.team_id, user.email) if previous_invitation is not None: cls.logger().info( f"Deleting old invitation for user {add_data.add_user_id} to team " f"#{add_data.authentication.team_id}.") TeamDatabaseClient.delete_invite(previous_invitation) DatabaseClient.commit() added_user = TeamUser(user_id=add_data.add_user_id, team_id=add_data.authentication.team_id) try: TeamDatabaseClient.add_team_user(added_user) DatabaseClient.commit() BotService.tito_welcome(added_user.user_id, added_user.team_id) cls.logger().info( f"Added user #{added_user.user_id} to team #{added_user.team_id} by admin #{admin.id}." ) return SuccessfulTeamMessageResponse( "User added.", TeamResponseStatus.ADDED.value) except IntegrityError: DatabaseClient.rollback() cls.logger().error( f"Couldn't add user #{added_user.user_id} to team #{added_user.team_id}." ) return UnsuccessfulTeamMessageResponse( "Couldn't invite user to team.")
def test_team_bots_return_team_bots_list_without_token(self): data = MagicMock() '''Mocked outputs''' user = User(user_id=0) user.team_id = 0 bot1 = Bot(bot_id=1, name="Bot-Test1", callback=None, token="Test-Token") bot2 = Bot(bot_id=2, name="Bot-Test2", callback=None, token="Test-Token") bots = [bot1, bot2] sys.modules[ "models.authentication"].Authenticator.authenticate_team.return_value = user sys.modules[ "daos.bots"].BotDatabaseClient.get_team_bots.return_value = bots response = BotService.team_bots(data) self.assertEqual(UserResponseStatus.LIST.value, response.json().get("status")) self.assertEqual(1, response.json().get("bots")[0].get("id")) self.assertEqual(2, response.json().get("bots")[1].get("id")) self.assertEqual("Bot-Test1", response.json().get("bots")[0].get("name")) self.assertEqual("Bot-Test2", response.json().get("bots")[1].get("name")) self.assertIsNone(response.json().get("bots")[0].get("callback")) self.assertIsNone(response.json().get("bots")[1].get("callback")) self.assertFalse("token" in response.json().get("bots")[0]) self.assertFalse("token" in response.json().get("bots")[1]) self.assertIsInstance(response, SuccessfulBotListResponse)
def test_create_bot_with_correct_data_works_properly(self): data = MagicMock() '''Mocked outputs''' mod = User(user_id=0) mod.team_id = 0 def add_client(): from tests.test_services import test_bots client = RegularClient(client_id=0) MockedBotDatabase.batch_clients = client return client def add_bot(bot): from tests.test_services import test_bots MockedBotDatabase.batch_bots = bot def add_team_bot(team_bot): from tests.test_services import test_bots MockedBotDatabase.batch_team_bots = team_bot def commit(): from tests.test_services import test_bots MockedBotDatabase.stored_clients += [ MockedBotDatabase.batch_clients ] MockedBotDatabase.stored_bots += [MockedBotDatabase.batch_bots] MockedBotDatabase.stored_team_bots += [ MockedBotDatabase.batch_team_bots ] MockedBotDatabase.batch_clients = None MockedBotDatabase.batch_bots = None MockedBotDatabase.batch_team_bots = None sys.modules[ "models.authentication"].Authenticator.authenticate_team.return_value = mod sys.modules["daos.users"].UserDatabaseClient.add_client = MagicMock( side_effect=add_client) sys.modules["daos.bots"].BotDatabaseClient.add_bot = MagicMock( side_effect=add_bot) sys.modules["daos.teams"].TeamDatabaseClient.add_team_user = MagicMock( side_effect=add_team_bot) sys.modules["daos.database"].DatabaseClient.commit = MagicMock( side_effect=commit) response = BotService.create_bot(data) self.assertIsNone(MockedBotDatabase.batch_bots) self.assertIsNone(MockedBotDatabase.batch_clients) self.assertIsNone(MockedBotDatabase.batch_team_bots) self.assertEqual(1, len(MockedBotDatabase.stored_bots)) self.assertEqual(0, MockedBotDatabase.stored_bots[0].id) self.assertEqual(1, len(MockedBotDatabase.stored_clients)) self.assertEqual(0, MockedBotDatabase.stored_clients[0].id) self.assertEqual(1, len(MockedBotDatabase.stored_team_bots)) self.assertEqual(0, MockedBotDatabase.stored_team_bots[0].user_id) self.assertEqual(0, MockedBotDatabase.stored_team_bots[0].team_id) self.assertEqual(TeamRoles.BOT.value, MockedBotDatabase.stored_team_bots[0].role) self.assertEqual(UserResponseStatus.OK.value, response.status) self.assertIsInstance(response, SuccessfulUserMessageResponse)
def test_create_bot_with_name_in_use_returns_bad_request(self): data = MagicMock() '''Mocked outputs''' mod = User(user_id=0) mod.team_id = 0 def add_client(): from tests.test_services import test_bots client = RegularClient(client_id=0) MockedBotDatabase.batch_clients = client return client def add_bot(bot): from tests.test_services import test_bots MockedBotDatabase.batch_bots = bot def add_team_bot(team_bot): from tests.test_services import test_bots MockedBotDatabase.batch_team_bots = team_bot def commit(): raise IntegrityError(mock, mock, mock) def rollback(): from tests.test_services import test_bots MockedBotDatabase.batch_clients = None MockedBotDatabase.batch_bots = None MockedBotDatabase.batch_team_bots = None sys.modules[ "models.authentication"].Authenticator.authenticate_team.return_value = mod sys.modules["daos.users"].UserDatabaseClient.add_client = MagicMock( side_effect=add_client) sys.modules["daos.bots"].BotDatabaseClient.add_bot = MagicMock( side_effect=add_bot) sys.modules["daos.teams"].TeamDatabaseClient.add_team_user = MagicMock( side_effect=add_team_bot) sys.modules["daos.database"].DatabaseClient.commit = MagicMock( side_effect=commit) sys.modules["daos.database"].DatabaseClient.rollback = MagicMock( side_effect=rollback) sys.modules[ "daos.bots"].BotDatabaseClient.get_bot_by_name.return_value = MagicMock( ) response = BotService.create_bot(data) self.assertIsNone(MockedBotDatabase.batch_bots) self.assertIsNone(MockedBotDatabase.batch_clients) self.assertIsNone(MockedBotDatabase.batch_team_bots) self.assertEqual(0, len(MockedBotDatabase.stored_bots)) self.assertEqual(0, len(MockedBotDatabase.stored_clients)) self.assertEqual(0, len(MockedBotDatabase.stored_team_bots)) self.assertEqual(UserResponseStatus.ALREADY_REGISTERED.value, response.status) self.assertIsInstance(response, BadRequestUserMessageResponse)
def test_bot_mention_not_sent_when_bot_not_found(self): client_id = 0 message = Message(message_id=0, sender_id=1, receiver_id=2, team_id=0, content="@test hola", send_type=SendMessageType.CHANNEL, message_type=MessageType.TEXT) '''Mocked outputs''' bot = None def post(url, json, headers): from tests.test_services import test_bots MockedBotDatabase.posted_json = json sys.modules[ "daos.bots"].BotDatabaseClient.get_bot_by_id.return_value = bot sys.modules["requests"].post = MagicMock(side_effect=post) BotService.process_mention(client_id, message) self.assertIsNone(MockedBotDatabase.posted_json)
def create_team(cls, new_team_data): user = Authenticator.authenticate(new_team_data) new_team = Team(name=new_team_data.team_name, picture=new_team_data.picture, location=new_team_data.location, description=new_team_data.description, welcome_message=new_team_data.welcome_message) try: team = TeamDatabaseClient.add_team(new_team) new_team.id = team.id new_user_by_team = TeamUser(user_id=user.id, team_id=team.id, role=TeamRoles.CREATOR.value) TeamDatabaseClient.add_team_user(new_user_by_team) BotService.register_tito_in_team(team.id) DatabaseClient.commit() cls.logger().info(f"Team #{team.id} created.") cls.logger().info( f"User #{user.id} assigned as team #{team.id} {new_user_by_team.role}." ) except IntegrityError: DatabaseClient.rollback() if TeamDatabaseClient.get_team_by_name( new_team_data.team_name) is not None: cls.logger().info( f"Failing to create team {new_team_data.team_name}. Name already in use." ) return BadRequestTeamMessageResponse( f"Name {new_team_data.team_name} already in use for other team.", TeamResponseStatus.ALREADY_REGISTERED.value) else: cls.logger().error( f"Failing to create team {new_team_data.team_name}.") return UnsuccessfulTeamMessageResponse("Couldn't create team.") else: return SuccessfulTeamResponse(new_team, TeamResponseStatus.CREATED.value)
def test_register_tito_in_team_without_unknown_sqlalchemy_error_does_add_bot_to_team( self): team_id = 0 def add_team_bot(team_bot): from tests.test_services import test_bots MockedBotDatabase.batch_team_bots = team_bot def commit(): from tests.test_services import test_bots MockedBotDatabase.stored_team_bots += [ MockedBotDatabase.batch_team_bots ] MockedBotDatabase.batch_team_bots = None sys.modules["daos.teams"].TeamDatabaseClient.add_team_user = MagicMock( side_effect=add_team_bot) sys.modules["daos.database"].DatabaseClient.commit = MagicMock( side_effect=commit) BotService.register_tito_in_team(team_id) self.assertIsNone(MockedBotDatabase.batch_team_bots) self.assertEqual(1, len(MockedBotDatabase.stored_team_bots))
def get_team_bots(team_id): logger.info(f"Attempting to get team #{team_id}'s bots.") req = ClientRequest(request) response = BotService.team_bots(req.team_authentication_data(team_id)) return jsonify(response.json()), response.status_code()
def register_bot(): logger.info(f"Attempting to register new bot in team.") req = ClientRequest(request) response = BotService.create_bot(req.new_bot_data()) return jsonify(response.json()), response.status_code()