def test_get_reminders_ok(self) -> None: """ Test the function that obtains the list of reminders of a user, with success. """ # Prepare the mocks reminder_1 = models.Reminder(10, 1, 1) reminder_1.id = 1 reminder_2 = models.Reminder(50, 2, 1) reminder_2.id = 2 db_calls_mock.get_reminders_user.return_value = [reminder_1, reminder_2] response_reminder: response_models.Reminder = unittest.mock.MagicMock() response_reminder.anticipation_minutes = 10 show_session = models.ShowSession(None, None, datetime.datetime(2020, 1, 1), 5, 10) channel = models.Channel(None, 'Channel Name') show_data = models.ShowData('_Show_Name_', 'Show Name') show_data.is_movie = True complete_session = (show_session, channel, show_data) show_session_2 = models.ShowSession(None, None, datetime.datetime(2020, 2, 2), 15, 20) channel_2 = models.Channel(None, 'Channel Name 2') show_data_2 = models.ShowData('_Show_Name_2_', 'Show Name 2') show_data_2.is_movie = False complete_session_2 = (show_session_2, channel_2, show_data_2) db_calls_mock.get_show_session_complete.side_effect = [complete_session, complete_session_2] # Call the function actual_result = reminders.get_reminders(self.session, 1) # Verify the result self.assertEqual(2, len(actual_result)) self.assertEqual(1, actual_result[0].id) self.assertEqual('Show Name', actual_result[0].title) self.assertEqual(datetime.datetime(2020, 1, 1), actual_result[0].date_time) self.assertEqual(10, actual_result[0].anticipation_minutes) self.assertEqual(2, actual_result[1].id) self.assertEqual('Show Name 2', actual_result[1].title) self.assertEqual(datetime.datetime(2020, 2, 2), actual_result[1].date_time) self.assertEqual(50, actual_result[1].anticipation_minutes) # Verify the calls to the mocks db_calls_mock.get_reminders_user.assert_called_with(self.session, 1) db_calls_mock.get_show_session_complete.assert_has_calls( [unittest.mock.call(self.session, 1), unittest.mock.call(self.session, 2)])
async def _full_guild_add(session, guild): # add guild to database try: new_guild = models.Guild(id=guild.id, name=guild.name) session.add(new_guild) # we need to add all channels for channel in guild.channels: # add channel to database new_channel = models.Channel(id=channel.id, guild_id=guild.id, name=channel.name, channeltype=channel.type.name) session.add(new_channel) # we need to add all roles for role in guild.roles: # add role to database new_role = models.Role( id=role.id, guild_id=guild.id, name=role.name, ) session.add(new_role) session.commit() except Exception as e: session.rollback() logging.error(e) finally: session.close()
async def channels_create(self: Controller, params: Dict[str, Any]) -> Dict[str, Any]: try: await validator.validate("channels_create", params) except validator.ValidationError: raise errors.RequestValidationFailed try: token = await tokens.parse(params["token"]) except tokens.ParseError: raise errors.InvalidToken cu_query = await self.storage.get_users() cu_query.add(cu_query.equals("id", token["id"])) try: current_user = await cu_query.fetch_one() except errors.StorageException: raise errors.InternalError channel = models.Channel(creator_id=current_user.id, name=params["name"]) if "photo" in params: channel.photo = params["photo"] try: channel.id = await self.storage.store_channel(channel) except errors.StorageException: raise errors.InternalError result = {"id": channel.id} return result
async def fetch_one(self) -> models.Channel: query = ("SELECT id, creator_id, name, photo, deleted FROM channels") query = self.__format_query(query) channel = models.Channel() try: result = await self.storage.performer().fetchrow( query, *self.params) except Exception as e: await logger.warning(e) raise errors.StorageException if result is None: return channel channel.id = result["id"] channel.creator_id = result["creator_id"] channel.name = result["name"] channel.photo = result["photo"] channel.deleted = result["deleted"] return channel
async def fetch(self) -> List[models.Channel]: query = ("SELECT id, creator_id, name, photo, deleted FROM channels") query = self.__format_query(query) channels = [] try: results = await self.storage.performer().fetch(query, *self.params) except Exception as e: await logger.warning(e) raise errors.StorageException if results is None: return channels for result in results: channel = models.Channel() channel.id = result["id"] channel.creator_id = result["creator_id"] channel.name = result["name"] channel.photo = result["photo"] channel.deleted = result["deleted"] channels.append(channel) return channels
def add_channel(): if current_user.type != 'Brand/Agency': flash('You cannot add a channel if don\'t have one!') return redirect(url_for('marketplace')) form = CreateChannelForm() if form.validate_on_submit(): try: # some magic with api inside ChannelInfo object ci = ChannelInfo(form.link.data) if models.Channel.query.filter_by( link=form.link.data.lower()).first(): flash('Such marketplace already exists') return redirect(url_for('add_channel')) form.name.data = ci.name new_channel = models.Channel(name=ci.name, link=ci.chat_id, description=form.description.data, subscribers=ci.subscribers, price=form.price.data, secret=getrandompassword(), category=form.category.data, image=ci.photo, admin_id=current_user.id) flash( 'Great! Now you can confirm ownership in account settings section.' ) db.session.add(new_channel) db.session.commit() return redirect(url_for('marketplace')) except NameError: flash('No such channel found or incorrect link given') return redirect(url_for('add_channel')) return render_template('add_channel.html', form=form)
async def configure_channel_command(command, db_channel): """ Configure a channel with the given settings. If this channel does not yet exit in the DB, then create it. :param command: the command used. :param db_channel: the corresponding channel entry in the DB. """ # Make sure the user changing the channel settings is an admin if not command.author.guild_permissions.administrator: msg = 'Only server administrators can change a channel\'s settings.' await auxiliary.send_temp_message(msg, command.channel) return # The ids of the Discord channel and server where the message was sent discord_channel_id = command.channel.id discord_server_id = command.guild.id # Get the list of parameters in the message params = auxiliary.parse_command_parameters(command.content) # If the command has an invalid number of parameters if len(params) != 2: return # Filter the chosen setting delete_commands = False delete_all = False if params[1] == '-dc': delete_commands = True elif params[1] == '-da': delete_all = True elif params[1] == '-ka': delete_all = False delete_commands = False # Create or modify the channel with the correct configurations if db_channel is None: db_channel = models.Channel(discord_channel_id, discord_server_id, delete_commands, delete_all) config.session.add(db_channel) else: db_channel.delete_commands = delete_commands db_channel.delete_all = delete_all config.session.commit() print('Channel %s from %s was configured -> %s!' % (command.channel.name, command.guild.name, command.content))
async def _full_guild_sync(session, guild): # sync guild to database try: if session.query( exists().where(models.Guild.id == guild.id)).scalar(): session.query(models.Guild) \ .filter(models.Guild.id == guild.id, models.Guild.name != guild.name) \ .update({models.Guild.name: guild.name}) else: new_guild = models.Guild(id=guild.id, name=guild.name) session.add(new_guild) # we need to sync all channels for channel in guild.channels: # sync channel to database if session.query(exists().where( models.Channel.id == channel.id)).scalar(): session.query(models.Channel).filter( models.Channel.id == channel.id, models.Channel.name != channel.name).update( {models.Channel.name: channel.name}) else: new_channel = models.Channel(id=channel.id, guild_id=guild.id, name=channel.name, channeltype=channel.type.name) session.add(new_channel) # we need to sync all roles for role in guild.roles: # sync role to database if session.query( exists().where(models.Role.id == role.id)).scalar(): session.query(models.Role) \ .filter(models.Role.id == role.id, models.Role.name != role.name) \ .update({models.Role.name: role.name}) else: new_role = models.Role(id=role.id, guild_id=guild.id, name=role.name) session.add(new_role) session.commit() except Exception as e: session.rollback() logging.error(e) finally: session.close()
async def on_guild_channel_create(self, channel): try: # init new session session = self.db.Session() new_channel = models.Channel(id=channel.id, guild_id=channel.guild.id, name=channel.name, channeltype=channel.type.name) session.add(new_channel) except Exception as e: logging.error(e) finally: session.close()
def create_channel(command: discord.message.Message) -> models.Channel: """ Create a channel in the DB that represents the Discord channel where the message was sent. :param command: the message/command. """ # The ids of the Discord channel and server where the message was sent discord_channel_id = command.channel.id discord_server_id = command.guild.id db_channel = models.Channel(discord_channel_id, discord_server_id) config.session.add(db_channel) config.session.commit() return db_channel
def get_channel_from_dict(channel_dict): title = channel_dict.get('title') body = channel_dict.get('body', None) created_timestamp = channel_dict.get('created', 0) // 1000 created_date = datetime.datetime.fromtimestamp(created_timestamp).date() image = channel_dict.get('image', None) is_featured = channel_dict.get('isFeatured', False) link = channel_dict.get('link', None) slug = channel_dict.get('slug', None) updated_timestamp = channel_dict.get('updated', 0) // 1000 updated = datetime.datetime.fromtimestamp(updated_timestamp).date() return models.Channel(title=title, body=body, created_date=created_date, image=image, is_featured=is_featured, link=link, slug=slug, updated=updated)
def test_process_alarms_ok_02(self) -> None: """ Test the function process_alarms with an alarm that gets two matches. """ # 1 - Prepare the mocks # The db_calls.get_user_id in process_alarms user = models.User('email', 'pasword', 'pt') user.id = 933 db_calls_mock.get_user_id.return_value = user # The db_calls.get_alarms in process_alarms alarm = models.Alarm(None, 123, True, response_models.AlarmType.DB.value, None, None, 933) db_calls_mock.get_alarms.return_value = [alarm] # The db_calls.get_show_titles in get_show_titles show_titles = models.ShowTitles(123, True, 'Title 1|Title 2') show_titles.insertion_datetime = datetime.datetime.utcnow( ) - datetime.timedelta(hours=3) db_calls_mock.get_show_titles.return_value = show_titles # The db_calls.get_last_update in process_alarms -> search_sessions_db_with_tmdb_id -> # get_last_update_alarms_datetime original_datetime = datetime.datetime(2020, 8, 1, 9) last_update = models.LastUpdate(None, original_datetime) db_calls_mock.get_last_update.return_value = last_update # The db_calls.search_show_sessions_data_with_tmdb_id in process_alarms -> search_sessions_db_with_tmdb_id channel = models.Channel('CH', 'Channel') channel.id = 76 show_data = models.ShowData('search title', 'Título') show_data.id = 27 show_data.tmdb_id = 123 show_session = models.ShowSession( None, None, original_datetime + datetime.timedelta(days=2), 76, 27) show_session.update_timestamp = datetime.datetime.utcnow( ) + datetime.timedelta(hours=38) db_calls_mock.search_show_sessions_data_with_tmdb_id.return_value = [ (show_session, channel, show_data) ] # The db_calls.get_user_excluded_channels in process_alarms -> search_sessions_db_with_tmdb_id channel_2 = models.Channel('CH2', 'Channel 2') channel_2.id = 981 user_excluded_channel = models.UserExcludedChannel(933, 981) db_calls_mock.get_user_excluded_channels.return_value = [ user_excluded_channel ] # The db_calls.get_last_update in process_alarms -> search_sessions_db -> get_last_update_alarms_datetime # has been done with return_value # The db_calls.get_user_excluded_channels in process_alarms -> search_sessions_db db_calls_mock.get_user_excluded_channels.return_value = [ user_excluded_channel ] # The db_calls.search_show_sessions_data in process_alarms -> search_sessions_db for 'Title 1' show_session_2 = models.ShowSession( None, None, original_datetime + datetime.timedelta(days=3), 76, 27) show_session_2.update_timestamp = datetime.datetime.utcnow( ) + datetime.timedelta(hours=38) db_calls_mock.search_show_sessions_data.side_effect = [[ (show_session_2, channel, show_data) ], []] # The db_calls.search_show_sessions_data in process_alarms -> search_sessions_db # for 'Title 1' has been done with side_effect # The process_emails.set_language in process_alarms is void # The process_emails.send_alarms_email in process_alarms process_emails_mock.send_alarms_email.return_value = True # The db_calls.get_last_update in process_alarms has been done with return_value # The db_calls.commit in process_alarms db_calls_mock.commit.return_value = True # 2 - Call the function processing.process_alarms(self.session) # 3 - Verify the results self.assertTrue(last_update.alarms_datetime > original_datetime) # Verify the calls to the mocks db_calls_mock.get_user_id.assert_called_with(self.session, 933) db_calls_mock.get_alarms.assert_called_with(self.session) db_calls_mock.get_show_titles.assert_called_with( self.session, 123, True) db_calls_mock.get_last_update.assert_has_calls([ unittest.mock.call(self.session), unittest.mock.call(self.session), unittest.mock.call(self.session) ]) db_calls_mock.search_show_sessions_data_with_tmdb_id.assert_called_with( self.session, 123, True, None, None, below_datetime=original_datetime) db_calls_mock.get_user_excluded_channels.assert_has_calls([ unittest.mock.call(self.session, 933), unittest.mock.call(self.session, 933) ]) db_calls_mock.search_show_sessions_data.assert_has_calls([ unittest.mock.call(self.session, '_Title_1_', True, None, None, False, True, below_datetime=original_datetime, ignore_with_tmdb_id=True), unittest.mock.call(self.session, '_Title_2_', True, None, None, False, True, below_datetime=original_datetime, ignore_with_tmdb_id=True) ]) process_emails_mock.set_language.assert_called_with('pt') send_alarms_email_calls = process_emails_mock.send_alarms_email.call_args_list self.assertEqual(1, len(send_alarms_email_calls)) call_args, _ = send_alarms_email_calls[0] self.assertEqual('email', call_args[0]) actual_results = call_args[1] self.assertEqual(2, len(actual_results)) self.assertEqual(response_models.LocalShowResultType.TV, actual_results[0].type) self.assertEqual('Título', actual_results[0].show_name) self.assertEqual('Channel', actual_results[0].service_name) self.assertEqual(original_datetime + datetime.timedelta(days=2), actual_results[0].date_time) self.assertEqual(response_models.LocalShowResultType.TV, actual_results[1].type) self.assertEqual('Título', actual_results[1].show_name) self.assertEqual('Channel', actual_results[1].service_name) self.assertEqual(original_datetime + datetime.timedelta(days=3), actual_results[1].date_time) db_calls_mock.commit.assert_called_with(self.session)
def test_delete_old_sessions(self) -> None: """ Test the function delete_old_sessions. """ # The expected result expected_result = 2 # Prepare the mocks # Prepare the call to search_old_sessions show_session_1 = models.ShowSession(None, None, datetime.datetime(2020, 1, 1), 5, 10) show_session_1.id = 1 show_session_2 = models.ShowSession(1, 10, datetime.datetime(2020, 2, 2), 8, 25) show_session_2.id = 2 db_calls_mock.search_old_sessions.return_value = [ show_session_1, show_session_2 ] # Prepare the call to get_reminders_session for session 1 and session 2 reminder_1 = models.Reminder(10, 1, 7) reminder_1.id = 1 reminder_2 = models.Reminder(50, 1, 4) reminder_2.id = 2 reminders_session_1 = [reminder_1, reminder_2] reminders_session_2 = [] db_calls_mock.get_reminders_session.side_effect = [ reminders_session_1, reminders_session_2 ] # Prepare the call to get_show_session_complete for session 1 channel = models.Channel(None, 'Channel Name') show_data = models.ShowData('_Show_Name_', 'Show Name') show_data.is_movie = True complete_session = (show_session_1, channel, show_data) db_calls_mock.get_show_session_complete.return_value = complete_session # Prepare the call to get_user_id for reminder 1 and reminder 2 user_7 = models.User('*****@*****.**', 'password', 'pt') user_7.id = 7 user_4 = models.User('*****@*****.**', 'password', 'pt') user_4.id = 4 db_calls_mock.get_user_id.side_effect = [user_7, user_4] # Prepare the call to send_deleted_sessions_email for user 7 and user 4 process_emails_mock.send_deleted_sessions_email.return_value = True # Call the function start_datetime = datetime.datetime.utcnow() - datetime.timedelta( days=2) end_datetime = datetime.datetime.utcnow() channels = ['Odisseia'] actual_result = get_file_data.delete_old_sessions( self.session, start_datetime, end_datetime, channels) # Verify the result self.assertEqual(expected_result, actual_result) # Verify the calls to the mocks db_calls_mock.search_old_sessions.assert_called_with( self.session, start_datetime, end_datetime, channels) db_calls_mock.get_reminders_session.assert_has_calls([ unittest.mock.call(self.session, 1), unittest.mock.call(self.session, 2) ]) db_calls_mock.get_show_session_complete.assert_called_with( self.session, 1) db_calls_mock.get_user_id.assert_has_calls([ unittest.mock.call(self.session, 7), unittest.mock.call(self.session, 4) ]) process_emails_mock.send_deleted_sessions_email.assert_has_calls([ unittest.mock.call('*****@*****.**', unittest.mock.ANY), unittest.mock.call('*****@*****.**', unittest.mock.ANY) ]) self.session.delete.assert_has_calls([ unittest.mock.call(reminder_1), unittest.mock.call(reminder_2), unittest.mock.call(show_session_1), unittest.mock.call(show_session_2) ])
def test_process_reminders_ok_02(self) -> None: """ Test the function that processes reminders, with success. """ # Prepare the mocks now = datetime.datetime.utcnow() show_session_1 = models.ShowSession(None, None, now + datetime.timedelta(minutes=30), 5, 10) show_session_1.id = 1 show_session_2 = models.ShowSession(2, 10, now + datetime.timedelta(minutes=100), 10, 15) show_session_2.id = 2 show_session_3 = models.ShowSession(None, None, now + datetime.timedelta(days=15), 10, 10) show_session_3.id = 3 channel_5 = models.Channel(None, 'Channel 5') channel_10 = models.Channel(None, 'Channel 10') show_data_10 = models.ShowData('Show 10', 'Show 10') show_data_10.is_movie = True show_data_15 = models.ShowData('Show 15', 'Show 15') show_data_15.is_movie = False reminder_1 = models.Reminder(60, 1, 1) reminder_session_1 = (reminder_1, show_session_1) reminder_2 = models.Reminder(120, 2, 2) reminder_session_2 = (reminder_2, show_session_2) reminder_3 = models.Reminder(60, 1, 2) reminder_session_3 = (reminder_3, show_session_1) # This session is still too far reminder_4 = models.Reminder(60, 3, 3) reminder_session_4 = (reminder_4, show_session_3) db_calls_mock.get_sessions_reminders.return_value = [reminder_session_1, reminder_session_2, reminder_session_3, reminder_session_4] show_session_tuple_1 = (show_session_1, channel_5, show_data_10) show_session_tuple_2 = (show_session_2, channel_10, show_data_15) show_session_tuple_3 = (show_session_1, channel_5, show_data_10) db_calls_mock.get_show_session_complete.side_effect = [show_session_tuple_1, show_session_tuple_2, show_session_tuple_3] db_calls_mock.get_user_id.side_effect = [models.User('*****@*****.**', 'password', 'pt'), models.User('*****@*****.**', 'password', 'en'), models.User('*****@*****.**', 'password', 'en')] process_emails_mock.send_alarms_email.side_effect = [True, True, True] # Call the function reminders.process_reminders(self.session) # Verify the calls to the mocks db_calls_mock.get_sessions_reminders.assert_has_calls(self.session) db_calls_mock.get_show_session_complete.assert_has_calls([unittest.mock.call(self.session, 1), unittest.mock.call(self.session, 2), unittest.mock.call(self.session, 1)]) db_calls_mock.get_user_id.assert_has_calls([unittest.mock.call(self.session, 1), unittest.mock.call(self.session, 2), unittest.mock.call(self.session, 2)]) process_emails_mock.set_language.assert_has_calls([unittest.mock.call('pt'), unittest.mock.call('en'), unittest.mock.call('en')]) # Given that it can't compare the object sent in the email self.assertEqual(3, process_emails_mock.send_reminders_email.call_count)
def test_Odisseia_add_file_data(self) -> None: """ Test the function Odisseia.add_file_data with a new session of a show with a matching channel correction. An old event was added to show that nothing changes and it is ignored. """ # Prepare the mocks # Replace datetime class with a utility class with a fixed datetime datetime.datetime = NewDatetime # Prepare the call to get_channel_name channel_data = models.Channel('Acronym', 'Channel Name') channel_data.id = 8373 db_calls_mock.get_channel_name.return_value = channel_data # Prepare the call to search_channel_show_data channel_show_data = models.ChannelShowData(8373, 2, False, 'Attack and Defend', 'Ataque e Defesa') channel_show_data.show_id = 51474 db_calls_mock.search_channel_show_data_correction.return_value = channel_show_data # Prepare the call to get_show_data_id show_data = models.ShowData('Search Title', 'Localized Title') show_data.id = 51474 db_calls_mock.get_show_data_id.return_value = show_data # Prepare the call to search_existing_session db_calls_mock.search_existing_session.return_value = None # Prepare the call to register_show_session show_session = models.ShowSession( 1, 5, datetime.datetime(2021, 3, 19, 5, 15, 16), 8373, 51474) db_calls_mock.register_show_session.return_value = show_session # Prepare the call to search_old_sessions db_calls_mock.search_old_sessions.return_value = [] # Call the function actual_result = file_parsers.odisseia.Odisseia.add_file_data( self.session, base_path + 'data/odisseia_example.xml', 'Odisseia') # Get back the datetime.datetime datetime.datetime = self.datetime_backup # Verify the result self.assertEqual(datetime.datetime(2021, 3, 19, 5, 10, 16), actual_result.start_datetime) self.assertEqual(datetime.datetime(2021, 3, 19, 5, 20, 16), actual_result.end_datetime) self.assertEqual(1, actual_result.total_nb_sessions_in_file) self.assertEqual(0, actual_result.nb_updated_sessions) self.assertEqual(1, actual_result.nb_added_sessions) self.assertEqual(0, actual_result.nb_deleted_sessions) # Verify the calls to the mocks db_calls_mock.get_channel_name.assert_called_with( self.session, 'Odisseia') db_calls_mock.search_channel_show_data_correction.assert_called_with( self.session, 8373, False, 'Attack and Defend', 'Ataque e Defesa', directors=['Seaton McLean'], year=2015, subgenre='Natureza', creators=None) db_calls_mock.get_show_data_id.assert_called_with(self.session, 51474) db_calls_mock.search_existing_session.assert_called_with( self.session, 1, 5, datetime.datetime(2021, 3, 19, 5, 15, 16), 8373, 51474) db_calls_mock.register_show_session.assert_called_with( self.session, 1, 5, datetime.datetime(2021, 3, 19, 5, 15, 16), 8373, 51474, audio_language=None, extended_cut=False, should_commit=False) db_calls_mock.search_old_sessions.assert_called_with( self.session, datetime.datetime(2021, 3, 19, 5, 10, 16), datetime.datetime(2021, 3, 19, 5, 20, 16), ['Odisseia'])