Beispiel #1
0
    def test_get_episode(self):
        ''' Tests getting episode from video's field. '''

        configure_for_unittest()
        from model import Video, Show, Season, Episode

        show = Show(title='House of Cards').save()
        season1 = Season(show=show, number=1).save()
        season2 = Season(show=show, number=2).save()
        episode1 = Episode(season=season1,
                           number=1,
                           release_date=dt(2010, 1, 1)).save()
        episode2 = Episode(season=season1, number=2).save()
        episode3 = Episode(season=season2, number=1).save()
        video = Video(link='vk.com').save()

        show.seasons.connect(season1)
        show.seasons.connect(season2)
        season1.episodes.connect(episode1)
        season1.episodes.connect(episode2)
        season2.episodes.connect(episode3)
        episode1.videos.connect(video)

        video.refresh()

        self.assertEqual(video.episode.get().number, 1)
Beispiel #2
0
    def merge_episode(episode_info):

        # Split the name
        path, info = episode_info
        show_name = info['series'].lower()
        parsed_season = info['season']
        parsed_episode = info['episodeNumber']

        try:
            show = Show.get(Show.name == show_name)
        except DoesNotExist:
            # Show does not exist yet
            show = Show.create(name=show_name)
            season = Season.create(show=show, season_number=parsed_season)
            Episode.create(season=season, episode_number=parsed_episode, path=path, added_time=datetime.datetime.now())
            print('Merged "' + show.name + '" season ' + str(parsed_season) + ' episode ' + str(parsed_episode))
        else:
            try:
                season = Season.get(Season.show == show, Season.season_number == parsed_season)
            except DoesNotExist:
                # Season did not exist yet
                season = Season.create(show=show, season_number=parsed_season)
                Episode.create(season=season, episode_number=parsed_episode, path=path,
                               added_time=datetime.datetime.now())
                print('Merged "' + show.name + '" season ' + str(parsed_season) + ' episode ' + str(parsed_episode))
            else:
                try:
                    Episode.get(Episode.season == season, Episode.episode_number == parsed_episode)
                except DoesNotExist:
                    Episode.create(season=season, episode_number=parsed_episode, path=path,
                                   added_time=datetime.datetime.now())
                    print('Merged "' + show.name + '" season ' + str(parsed_season) + ' episode ' + str(parsed_episode))
Beispiel #3
0
def listTR(seasonid_from, seasonid_to, ageid):
    # Список сезонов и возрастов по состоянию на текущий год, название начального и конечного сезонов и возраста
    listSeason = Season.select().order_by(Season.seasonName)
    listAge    = Age.select().order_by(Age.ageName)
    for age in listAge:
        age.ageName = int(date.today().year) - int(age.ageName)
    try:
        seasonname_from = Season.get(season_ID = seasonid_from).seasonName
        seasonname_to   = Season.get(season_ID = seasonid_to).seasonName
        agename         = Age.get(age_ID = ageid).ageName
    except DoesNotExist:
        seasonname_from = None
        seasonname_to   = None
        agename         = None

    # Список позиций рейтинга юношеских команд и их количество
    listTR = teamRating.select().where(teamRating.season_ID.between(seasonid_from, seasonid_to) & teamRating.age_ID == ageid)
    listTR_count = listTR.count()

    # Вывод шаблона
    return render_template(
        'teamRating.jinja.html', 
        listSeason    = listSeason, 
        seasonid_from = seasonid_from, 
        seasonid_to   = seasonid_to, 
        listAge       = listAge, 
        ageid         = ageid, 
        listTR        = listTR,
        listTR_count  = listTR_count)
Beispiel #4
0
def listSR(seasonid_from, seasonid_to):
    # Список сезонов /* и возрастов по состоянию на текущий год, название начального и конечного сезонов */ и возраста
    listSeason = Season.select().order_by(Season.seasonName)
    # listAge    = Age.select().order_by(Age.ageName)
    # for age in listAge:
    #     age.ageName = int(date.today().year) - int(age.ageName)
    try:
        seasonname_from = Season.get(season_ID = seasonid_from).seasonName
        seasonname_to   = Season.get(season_ID = seasonid_to).seasonName
        # agename         = Age.get(age_ID = ageid).ageName
    except DoesNotExist:
        seasonname_from = None
        seasonname_to   = None
        # agename         = None

    # Список позиций рейтинга спортивных школ и их количество
    listSR = schoolRating.select().where(schoolRating.season_ID.between(seasonid_from, seasonid_to))
    listSR_count = listSR.count()

    # Вывод шаблона
    return render_template(
        'schoolRating.jinja.html', 
        listSeason    = listSeason, 
        seasonid_from = seasonid_from, 
        seasonid_to   = seasonid_to, 
        # listAge       = listAge, 
        # ageid         = ageid, 
        listSR        = listSR,
        listSR_count  = listSR_count)
    def syncSeason(self, serie, season):
        qry = Session.query(Serie).filter_by(path=serie)
        if qry.count() == 0:
            raise Exception("No serie linked to %s/%s" % (serie, saison))
        serie = qry.one()

        path = season
        num = getSeasonNumFromFoldername(season)

        if num is None:
            raise Exception("This is not a season (%s)" % season)

        season = filter(lambda season: season.num == num, serie.seasons)
        if len(season) == 0:
            season = Season(num=num, path=path)
            Session.add(season)
            serie.seasons.append(season)
        else:
            assert 1 == len(season)
            season = season[0]
            season.num = num
            season.path = path

        episodes = glob(os.path.join(self.basepath, serie.path, season.path, "*"))
        episodes = filter(lambda episode: os.path.isfile(episode), episodes)

        for episode in [os.path.basename(e) for e in episodes]:
            try:
                self.syncEpisode(serie.path, season.path, episode)
            except:
                pass
Beispiel #6
0
def listSAS(seasonid, ageid):
    # Список сезонов и возрастов по состоянию на текущий год, название текущего сезона и возраста
    listSeason = Season.select().order_by(Season.season_ID.asc())
    listAge    = Age.select().order_by(Age.ageName)
    for age in listAge:
        age.ageName = int(date.today().year) - int(age.ageName)
    try:
        seasonname = Season.get(season_ID = seasonid).seasonName
        agename    = Age.get(age_ID = ageid).ageName
    except DoesNotExist:
        seasonname = None
        agename    = None

    # Список игровых стадий
    listStage    = Stage.select().order_by(Stage.stageType, Stage.stageName)
    # Список типов соревноавний
    listGameType = GameType.select().order_by(GameType.gameTypeName)
    # Список игровых этапов с количеством дочерних команд и матчей
    listSAS = (RawQuery(SAS, 
        'SELECT `SAS`.*, (SELECT COUNT(`SAST2`.`SAS_ID`) FROM `SeasonAgeStageTeam` AS `SAST2` WHERE `SAST2`.`SAS_ID` = `SAS`.`SAS_ID`) AS `countSAST`, (SELECT COUNT(`GP2`.`SAS_ID`) FROM `GameProtocol` AS `GP2` WHERE ((`GP2`.`SAS_ID` = `SAST`.`SAS_ID`) AND (`SAST`.`SAS_ID` = `SAS`.`SAS_ID` ))) AS `countGP` FROM `SeasonAgeStage` AS `SAS` LEFT JOIN `SeasonAgeStageTeam` AS `SAST` ON (`SAS`.`SAS_ID` = `SAST`.`SAS_ID`) LEFT JOIN `Stage` ON (`SAS`.`stage_ID` = `Stage`.`stage_ID`) WHERE ((`SAS`.`season_ID` = %s) AND (`SAS`.`age_ID` = %s)) GROUP BY `SAS`.`SAS_ID` ORDER BY `SAS`.`SAS_ID` ASC', seasonid, ageid))

    # Переменные для автозаполнения формы добавления/обновления данных в JS-скрипте шаблона
    ## Список полей
    modifyFields = ['stage', 'zoneGroupPlayoffToggle', 'gameType', 'startDate', 'finishDate']
    ## Список групп радиокнопок
    modifyRadios = ['zoneGroupPlayoffToggle', 'gameType']
    ## Список выпадающих списков
    modifySelect = ['stage']   
    ## Заголовки модального окна
    createHeader = ['"Создать новую игровую стадию"']
    updateHeader = ['"Изменить игровую стадию для возраста "', agename, '" в сезоне "', seasonname]
    ## Действия формы
    createAction = ['"/season/"', seasonid, '"/age/"', ageid, '"/stage/create"']
    updateAction = ['"/season/"', seasonid, '"/age/"', ageid, '"/stage/"', 'PK_ID', '"/update"']
    deleteAction = ['"/season/"', seasonid, '"/age/"', ageid, '"/stage/"', 'PK_ID', '"/delete"']

    # Вывод шаблона
    return render_template(
        'SAS.jinja.html', 
        listSeason   = listSeason,
        seasonid     = seasonid,
        seasonname   = seasonname,
        listAge      = listAge,
        ageid        = ageid,
        agename      = agename,
        listStage    = listStage,
        listGameType = listGameType,
        listSAS      = listSAS,
        modifyFields = modifyFields,
        modifyRadios = modifyRadios,
        modifySelect = modifySelect,
        createHeader = createHeader,
        updateHeader = updateHeader,
        createAction = createAction,
        updateAction = updateAction,
        deleteAction = deleteAction)
Beispiel #7
0
def createSeason():
    # Получение полей формы из шаблона
    seasonname = request.form['seasonName']

    # Сохранение новой записи в БД
    if session['demo']:
        pass
    else:
        Season.create(
            seasonName = seasonname)

    # Редирект на вид list
    return redirect(
        url_for('listSeason'))
Beispiel #8
0
def deleteSeason(seasonid):
    # Удаление текущей записи в БД
    if session['demo']:
        pass
    else:
        # Ограничение по внешнему ключу FK_SAS_Season 
        # не позволяет удалить стадию при наличии связанных с ней игровых этапов.
        try:
            Season.get(season_ID = seasonid).delete_instance()
        except IntegrityError:
            flash('Вы не можете удалить этот сезон, пока в нём добавлен хотя бы один игровой этап', 'danger')

    # Редирект на вид list
    return redirect(
        url_for('listSeason'))
Beispiel #9
0
def updateSeason(seasonid):
    # Получение полей формы из шаблона
    seasonname = request.form['seasonName']

    # Обновление текущей записи в БД
    if session['demo']:
        pass
    else:
        season            = Season()
        season.season_ID  = seasonid
        season.seasonName = seasonname
        season.save()

    # Редирект на вид list
    return redirect(
        url_for('listSeason'))
Beispiel #10
0
def listSeason():
    # Вывод списка сезонов
    listSeason = Season.select().order_by(Season.seasonName)

    # Переменные для автозаполнения формы добавления/обновления данных в JS-скрипте шаблона
    ## Список полей
    modifyFields = ['seasonName']
    ## Заголовки модального окна
    createHeader = ['"Создать новый сезон"']
    updateHeader = ['"Изменить "', 'seasonName']
    ## Действия формы
    createAction = ['"/season/create"']
    updateAction = ['"/season/"', 'PK_ID', '"/update"']
    deleteAction = ['"/season/"', 'PK_ID', '"/delete"']

    # Вывод шаблона
    return render_template(
        'Season.jinja.html', 
        listSeason = listSeason,
        modifyFields = modifyFields,
        createHeader = createHeader,
        updateHeader = updateHeader,
        createAction = createAction,
        updateAction = updateAction,
        deleteAction = deleteAction)
Beispiel #11
0
def scrape_league_history(country):
    league_name = countries_leagues[country]
    db.delete_league_by_name(league_name)

    browser.get(main_url)
    more_countries_element = browser.find_element_by_class_name('show-more')
    more_countries_button = more_countries_element.find_element_by_link_text('More')
    execute_script_click(more_countries_button)

    click_league(country, league_name)

    archive_button = browser.find_element_by_link_text('Archive')
    archive_button.click()

    season_names = browser.find_elements_by_class_name('leagueTable__season')[2:]
    season_names = [season.find_element_by_tag_name('a') for season in season_names][::-1]

    league = League(name=league_name, country=country)
    db.save_league(league)

    seasons = [Season(name=get_years_from_season_name(season_name.text), league=league) for season_name in season_names]
    links = [season.get_attribute('href') for season in season_names]

    for season, link in zip(seasons, links):
        scrape_table(link, league, season)
        scrape_results(link, league, season)
Beispiel #12
0
    def test_availability(self):
        ''' Tests availabity properties of object. '''

        configure_for_unittest()
        from model import Show, Season, Episode

        show = Show(title='House of Cards').save()
        season1 = Season(show=show, number=1).save()
        season2 = Season(show=show, number=2).save()
        episode1 = Episode(season=season1,
                           number=1,
                           release_date=dt(2010, 1, 1)).save()
        episode2 = Episode(season=season1, number=2).save()

        show.seasons.connect(season1)
        show.seasons.connect(season2)
        season1.episodes.connect(episode1)
        season1.episodes.connect(episode2)

        self.assertEqual(season1.available_episodes[0], episode1)
        self.assertEqual(season1.unavailable_episodes[0], episode2)
Beispiel #13
0
def add_or_update_show(title):

    # Обрабатываем отсутствие результатов поиска
    try:
        episodes, number_of_seasones, serial_title = parse_toramp(title)
    except ValueError as e:
        print '{} для {}'.format(e.message, title)
        return

    # Если сериал существует - работаем с ним
    try:
        show = Show.nodes.get(title_lower=serial_title.lower())
    except neomodel.DoesNotExist:
        show = Show(title=unicode(serial_title)).save()

    for i in xrange(number_of_seasones):

        # Если сезон уже существует - работаем с ним
        try:
            season = show.seasons.get(number=i+1)
        except neomodel.DoesNotExist:
            season = Season(show=show, number=i+1).save()
            show.seasons.connect(season)

        episodes_in_season = filter(lambda x: x['season'] == i + 1, episodes)

        for element in episodes_in_season:

            # Если эпизод уже есть - пропускаем
            try:
                episode = season.episodes.get(
                    number=element['number'],
                    title=element['title'],
                    release_date=element['release'],
                )

            except neomodel.DoesNotExist:
                episode = Episode(
                    season=season,
                    title=unicode(element['title']),
                    release_date=element['release'],
                    number=element['number'],
                    is_already_shown=element['release'] < datetime.datetime.now()
                ).save()
                season.episodes.connect(episode)
Beispiel #14
0
    def test_watch(self):
        ''' Tests responses on watch request. '''

        configure_for_unittest()
        from command import watch
        from model import Chat, Show, Season, Episode, Video

        chat = Chat(id=1).save()

        show = Show(title='House of Cards').save()
        season1 = Season(show=show, number=1).save()
        season2 = Season(show=show, number=2).save()
        episode1 = Episode(season=season1,
                           number=1,
                           release_date=dt(2010, 1, 1)).save()
        episode2 = Episode(season=season1, number=2).save()
        episode3 = Episode(season=season2, number=1).save()
        video1 = Video(link='link to video').save()
        video2 = Video(link='one more link').save()

        show.seasons.connect(season1)
        show.seasons.connect(season2)
        season1.episodes.connect(episode1)
        season1.episodes.connect(episode2)
        season2.episodes.connect(episode3)
        episode1.videos.connect(video1)
        episode1.videos.connect(video2)
        chat.rated_videos.connect(video1, {'value': 1})

        bot = FakeBot()
        upd = FakeUpdate(message=FakeMessage(chat=FakeChat(id=1)))

        # valid request
        upd.message.text = '/watch house of cards s1 e1'
        watch(bot, upd)

        self.assertEqual(bot.sended_message['text'], 'link to video')
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardMarkup)
        self.assertEqual(bot.sended_message['reply_markup'].keyboard,
                         [[Emoji.THUMBS_UP_SIGN, Emoji.THUMBS_DOWN_SIGN]])

        chat.referer = ''  # bot is waiting for feedback
        chat.save()

        # valid request - without arguments
        upd.message.text = '/watch'
        watch(bot, upd)

        chat.refresh()

        self.assertEqual('/watch', chat.referer)
        self.assertEqual(bot.sended_message['text'],
                         _('Which TV show would you like to see?'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)

        # valid request - continue with show_title
        upd.message.text = ' '.join([chat.referer, 'house of cards'])
        watch(bot, upd)

        chat.refresh()

        self.assertEqual(chat.referer, '/watch house of cards')
        self.assertEqual(bot.sended_message['text'],
                         _('Which season would you like to see?'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardMarkup)
        self.assertEqual(bot.sended_message['reply_markup'].keyboard, [['1']])

        # valid request - continue with seasons number
        upd.message.text = ' '.join([chat.referer, 's1'])
        watch(bot, upd)

        chat.refresh()

        self.assertEqual(chat.referer, '/watch house of cards s1')
        self.assertEqual(bot.sended_message['text'],
                         _('Which episode would you like to see?'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardMarkup)
        self.assertEqual(bot.sended_message['reply_markup'].keyboard, [['1']])

        # valid request - continue with episode number
        upd.message.text = ' '.join([chat.referer, 'e1'])
        watch(bot, upd)

        chat.refresh()

        self.assertEqual(chat.referer, '/rate link to video')
        self.assertEqual(bot.sended_message['text'], 'link to video')
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardMarkup)
        self.assertEqual(bot.sended_message['reply_markup'].keyboard,
                         [[Emoji.THUMBS_UP_SIGN, Emoji.THUMBS_DOWN_SIGN]])

        chat.referer = ''
        chat.save()

        # trying to watch non-existent TV show
        upd.message.text = '/watch kitchen'
        watch(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('This TV show is not available.'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)

        # trying to watch non-existent season
        upd.message.text = '/watch house of cards s5'
        watch(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('This season is not available.'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)

        # trying to watch unavailable season
        upd.message.text = '/watch house of cards s2 e1'
        watch(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('This season is not available.'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)

        # trying to watch non-existent episode
        upd.message.text = '/watch house of cards s1 e5'
        watch(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('This episode is not available.'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)

        # trying to watch unavailable episode
        upd.message.text = '/watch house of cards s1 e2'
        watch(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('This episode is not available.'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)
Beispiel #15
0
 def clear_model():
     Episode.delete()
     Season.delete()
     Show.delete()
Beispiel #16
0
    def test_rate(self):
        ''' Tests rating of video. '''

        configure_for_unittest()
        from command import rate
        from model import Chat, Show, Season, Episode, Video

        chat = Chat(id=1).save()

        show = Show(title='House of Cards').save()
        season1 = Season(show=show, number=1).save()
        season2 = Season(show=show, number=2).save()
        episode1 = Episode(season=season1,
                           number=1,
                           release_date=dt(2010, 1, 1)).save()
        episode2 = Episode(season=season1, number=2).save()
        episode3 = Episode(season=season2, number=1).save()
        video1 = Video(link='link to video').save()
        video2 = Video(link='one more link').save()

        show.seasons.connect(season1)
        show.seasons.connect(season2)
        season1.episodes.connect(episode1)
        season1.episodes.connect(episode2)
        season2.episodes.connect(episode3)
        episode1.videos.connect(video1)
        episode1.videos.connect(video2)
        chat.rated_videos.connect(video1, {'value': 1})

        bot = FakeBot()
        upd = FakeUpdate(message=FakeMessage(chat=FakeChat(id=1)))

        # positive review
        upd.message.text = ' '.join(
            ['/rate link to video',
             unicode(Emoji.THUMBS_UP_SIGN, 'utf-8')])
        rate(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('Thanks for the feedback!'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardHide)

        # negative review
        upd.message.text = ' '.join(
            ['/rate link to video',
             unicode(Emoji.THUMBS_DOWN_SIGN, 'utf-8')])
        rate(bot, upd)

        self.assertEqual(bot.sended_message['text'], 'one more link')
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardMarkup)
        self.assertEqual(bot.sended_message['reply_markup'].keyboard,
                         [[Emoji.THUMBS_UP_SIGN, Emoji.THUMBS_DOWN_SIGN]])

        # unknown review
        upd.message.text = ' '.join(['/rate link to video', 'unknown'])
        rate(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('Please rate the video.'))
        self.assertEqual(bot.sended_message['chat_id'], 1)
        self.assertEqual(type(bot.sended_message['reply_markup']),
                         ReplyKeyboardMarkup)
        self.assertEqual(bot.sended_message['reply_markup'].keyboard,
                         [[Emoji.THUMBS_UP_SIGN, Emoji.THUMBS_DOWN_SIGN]])

        chat.referer = ''
        chat.save()
Beispiel #17
0
    def test_default(self):
        ''' Tests responses on messages that are not commands. '''

        configure_for_unittest()
        from command import default, subscribe, unsubscribe, setlanguage, watch
        from model import Chat, Show, Season, Episode, Video

        chat = Chat(id=1).save()

        show = Show(title='House of Cards').save()
        season1 = Season(show=show, number=1).save()
        season2 = Season(show=show, number=2).save()
        episode1 = Episode(season=season1,
                           number=1,
                           release_date=dt(2010, 1, 1)).save()
        episode2 = Episode(season=season1, number=2).save()
        episode3 = Episode(season=season2, number=1).save()
        video1 = Video(link='link to video').save()
        video2 = Video(link='one more link').save()

        show.seasons.connect(season1)
        show.seasons.connect(season2)
        season1.episodes.connect(episode1)
        season1.episodes.connect(episode2)
        season2.episodes.connect(episode3)
        episode1.videos.connect(video1)
        episode1.videos.connect(video2)
        chat.rated_videos.connect(video1, {'value': 1})

        bot = FakeBot()
        upd = FakeUpdate(message=FakeMessage(chat=FakeChat(id=1)))

        # random input
        upd.message.text = 'random input'
        default(bot, upd)

        self.assertTrue('You can control' in bot.sended_message['text'])

        # subscribe in 2 steps
        upd.message.text = '/subscribe'
        subscribe(bot, upd)

        upd.message.text = 'house of cards'
        default(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('You have subscribed to the show.'))

        # unsubscribe in 2 steps
        upd.message.text = '/unsubscribe'
        unsubscribe(bot, upd)

        upd.message.text = 'house of cards'
        default(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('You have unsubscribed from the show.'))

        # setlanguage in 2 steps
        upd.message.text = '/setlanguage'
        setlanguage(bot, upd)

        upd.message.text = 'en'
        default(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('You are already using this language!'))

        # watch in 4 steps
        upd.message.text = '/watch'
        watch(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('Which TV show would you like to see?'))

        upd.message.text = 'house of cards'
        default(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('Which season would you like to see?'))

        upd.message.text = '1'
        default(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('Which episode would you like to see?'))

        upd.message.text = '1'
        default(bot, upd)

        self.assertEqual(bot.sended_message['text'], 'link to video')

        chat.referer = ''
        chat.save()

        # positive review - say 'thank you'
        upd.message.text = '/watch house of cards s1 e1'
        watch(bot, upd)

        upd.message.text = Emoji.THUMBS_UP_SIGN
        default(bot, upd)

        self.assertEqual(bot.sended_message['text'],
                         _('Thanks for the feedback!'))
Beispiel #18
0
def listSAST(seasonid, ageid, sasid):
    # Список сезонов и возрастов по состоянию на текущий год, название текущего сезона и возраста, название и тип игровой стадии текущего игрового этапа
    listSeason = Season.select().order_by(Season.season_ID.asc())
    listAge = Age.select().order_by(Age.ageName)
    for age in listAge:
        age.ageName = int(date.today().year) - int(age.ageName)
    try:
        seasonname = Season.get(season_ID = seasonid).seasonName
        agename    = Age.get(age_ID = ageid).ageName
        sasname    = SAS.get(SAS_ID = sasid).stage_ID.stageName
        sastype    = SAS.get(SAS_ID = sasid).stage_ID.stageType
    except DoesNotExist:
        seasonname = None
        agename    = None
        sasname    = None
        sastype    = None

    # Список игровых этапов по типам
    listSAS_Z = SAS.select().where(SAS.season_ID == seasonid, SAS.age_ID == ageid).join(Stage).where(Stage.stageType == "Z").order_by(Stage.stageName)
    listSAS_G = SAS.select().where(SAS.season_ID == seasonid, SAS.age_ID == ageid).join(Stage).where(Stage.stageType == "G").order_by(Stage.stageName)
    listSAS_P = SAS.select().where(SAS.season_ID == seasonid, SAS.age_ID == ageid).join(Stage).where(Stage.stageType == "P").order_by(Stage.stageName)

    # Список городов, спортивных школ и команд для фильтрации по связанным выпадающим спискам
    filterCity   =   City.select().order_by(City.cityName)
    filterSchool = School.select().order_by(School.schoolName)
    filterTeam   =   Team.select().order_by(Team.teamName)

    # Список команд в текущем игровом этапе
    listSAST  = SAST.select().where(SAST.SAS_ID == sasid).join(Stage, JOIN_LEFT_OUTER).order_by(SAST.SAST_ID)
    # Список игровых стадий
    listStage = Stage.select().order_by(Stage.stageType, Stage.stageName).order_by(Stage.stage_ID)

    # Есть ли в текущем игровом этапе подгруппы
    is_SASTsubstage  = SAST.select().where(SAST.SAS_ID == sasid).join(Stage).exists()
    # Список подгрупп текущего игрового этапа (если они есть)
    listSASTsubstage = SAST.select(SAST.substage_ID).distinct().where(SAST.SAS_ID == sasid).join(Stage, JOIN_LEFT_OUTER)

    # Переменные для автозаполнения формы добавления/обновления данных в JS-скрипте шаблона
    ## Список полей
    modifyFields = ['filterCity', 'filterSchool', 'filterTeam', 'substage_ID', 'stageType', 'stageName']
    ## Список групп радиокнопок
    modifyRadios = ['substage_ID']
    ## Список выпадающих списков
    modifySelect = ['filterCity', 'filterSchool', 'filterTeam']   
    ## Заголовки модального окна
    createHeader = ['"Добавить команду в "', 'stageType', '" "', 'stageName']
    updateHeader = ['"Изменить команду, участвующую в "', 'stageType', '" "', 'stageName']
    ## Действия формы
    createAction = ['"/season/"', seasonid, '"/age/"', ageid, '"/stage/"', sasid, '"/team/create"']
    updateAction = ['"/season/"', seasonid, '"/age/"', ageid, '"/stage/"', sasid, '"/team/"', 'PK_ID', '"/update"']
    deleteAction = ['"/season/"', seasonid, '"/age/"', ageid, '"/stage/"', sasid, '"/team/"', 'PK_ID', '"/delete"']

    # Вывод шаблона
    return render_template(
        'SAST.jinja.html', 
        listSeason       = listSeason,
        seasonid         = seasonid,
        seasonname       = seasonname,
        listAge          = listAge,
        ageid            = ageid,
        agename          = agename,
        listSAS_Z        = listSAS_Z,
        listSAS_G        = listSAS_G,
        listSAS_P        = listSAS_P,
        sasid            = sasid,
        sasname          = sasname,
        sastype          = sastype,
        filterCity       = filterCity,
        filterSchool     = filterSchool,
        filterTeam       = filterTeam,
        listSAST         = listSAST,
        listStage        = listStage,
        is_SASTsubstage  = is_SASTsubstage,
        listSASTsubstage = listSASTsubstage,
        modifyFields     = modifyFields,
        modifyRadios     = modifyRadios,
        modifySelect     = modifySelect,
        createHeader     = createHeader,
        updateHeader     = updateHeader,
        createAction     = createAction,
        updateAction     = updateAction,
        deleteAction     = deleteAction)