def main(api_token, timezone, live, today, matches, standings, league, sort_by,
         days, history, details, odds, not_started, refresh, bet, profile,
         all_bets, open_bets, closed_bets, watch_bets, possible_leagues):
    params = get_params(api_token, timezone)

    try:
        writer = get_writer()
        rh = RequestHandler(params, LEAGUES_DATA, writer, ch)
        betting = Betting(params, LEAGUES_DATA, writer, rh, ch)
        betting.main()

        Parameters = namedtuple(
            "parameters", "url, msg, league_name, sort_by, days, "
            "show_history, show_details, show_odds, not_started, refresh, place_bet, date_format, type_sort"
        )

        def get_multi_matches(filename, parameters):
            bets = betting.get_bets(ch.get_data('betting_files')[filename])
            match_ids = ','.join([i[0] for i in bets])
            predictions = [i[0] + ';' + i[1] for i in bets]
            return rh.get_multi_matches(match_ids, predictions, parameters)

        def bet_matches(type, sort_by):
            date_format = convert.format_date(ch.get('profile', 'date_format'))
            if sort_by is None:
                sort_by = 'date'
            parameters = Parameters('fixtures/multi', [
                "No open bets at the moment.",
                "There was problem getting live scores, check your parameters"
            ], None, sort_by, None, None, details, True, False, True, None,
                                    date_format, 'watch_bets')
            if type == 'open' and watch_bets:
                filename = 'open_bets'
                while True:
                    betting.check_open_bets()
                    quit = get_multi_matches(filename, parameters)
                    if quit:
                        return
                    else:
                        time.sleep(60)
            elif type == 'open':
                filename = 'open_bets'
            else:
                filename = 'closed_bets'

            get_multi_matches(filename, parameters)
            return

        if live or today or matches:
            check_options(history, bet, live, today, refresh, matches)
            date_format = convert.format_date(ch.get('profile', 'date_format'))
            if sort_by is None:
                sort_by = 'league'
            if bet:
                odds = True
            if live:
                not_started = False
                parameters = Parameters('livescores/now', [
                    "No live action at this moment",
                    "There was problem getting live scores, check your parameters"
                ], league, sort_by, days, history, details, odds, not_started,
                                        refresh, bet, date_format, "live")
            elif today:
                parameters = Parameters('livescores', [
                    "No matches today",
                    "There was problem getting today's scores, check your parameters"
                ], league, sort_by, days, history, details, odds, not_started,
                                        refresh, bet, date_format, "today")
            else:
                parameters = Parameters(
                    'fixtures/between/',
                    [[f"No matches in the past {str(days)} days."],
                     [f"No matches in the coming {str(days)} days."]], league,
                    sort_by, days, history, details, odds, not_started,
                    refresh, bet, date_format, "matches")
            rh.get_matches(parameters)
            return

        if standings:
            check_options_standings(league, history)
            rh.get_standings(league, details)
            return

        if profile:
            rh.show_profile()
            return

        if all_bets:
            betting.view_bets('open')
            betting.view_bets('closed')
            return

        if open_bets:
            if details:
                bet_matches('open', sort_by)
            else:
                betting.view_bets('open')
            return

        if closed_bets:
            if details:
                bet_matches('closed', sort_by)
            else:
                betting.view_bets('closed')
            return

        if watch_bets:
            bet_matches('open', sort_by)

        if possible_leagues:
            rh.show_leagues()
            return

    except IncorrectParametersException as e:
        click.secho(str(e), fg="red", bold=True)
예제 #2
0
class TestRequestHandler(unittest.TestCase):

    VALID_LEAGUE_CODE = "BL"
    VALID_TEAM_CODE = "AFC"
    VALID_TIME = 10

    def setUp(self):
        dummy_key = 12345678901234567890123456789012
        headers = {'X-Auth-Token': dummy_key}
        TEAM_DATA = get_team_data()["teams"]
        TEAM_NAMES = {team["code"]: team["id"] for team in TEAM_DATA}
        LEAGUE_IDS = leagueids.LEAGUE_IDS
        self.dummy_url = "http://some_url"
        writer = get_writer()
        self.rq = RequestHandler(headers, LEAGUE_IDS, TEAM_NAMES, writer)

    def tearDown(self):
        pass

    @mock.patch('requests.get')
    def test_ok_code(self, mock_call):
        mock_call.return_value = mock.MagicMock(
                status_code=requests.codes.ok,
                response=json.dumps({'key': 'value'}))
        try:
            self.rq._get(self.dummy_url)
        except APIErrorException:
            self.fail("Threw exception erroneously")

    @mock.patch('requests.get')
    def test_bad_code(self, mock_call):
        mock_call.return_value = mock.MagicMock(
                status_code=requests.codes.bad,
                response=json.dumps({'key': 'value'}))
        with self.assertRaises(APIErrorException) as context:
            self.rq._get(self.dummy_url)
        self.assertTrue("Invalid request. "
                        "Check parameters." in context.exception)

    @mock.patch('requests.get')
    def test_forbidden_code(self, mock_call):
        mock_call.return_value = mock.MagicMock(
                status_code=requests.codes.forbidden,
                response=json.dumps({'key': 'value'}))
        with self.assertRaises(APIErrorException) as context:
            self.rq._get(self.dummy_url)
        self.assertTrue('This resource is restricted' in context.exception)

    @mock.patch('requests.get')
    def test_not_found_code(self, mock_call):
        mock_call.return_value = mock.MagicMock(
                status_code=requests.codes.not_found,
                response=json.dumps({'key': 'value'}))
        with self.assertRaises(APIErrorException) as context:
            self.rq._get(self.dummy_url)
        self.assertTrue("This resource does not exist. "
                        "Check parameters" in context.exception)

    @mock.patch('requests.get')
    def test_too_many_requests_code(self, mock_call):
        mock_call.return_value = mock.MagicMock(
                status_code=requests.codes.too_many_requests,
                response=json.dumps({'key': 'value'}))
        with self.assertRaises(APIErrorException) as context:
            self.rq._get(self.dummy_url)
        self.assertTrue("You have exceeded your allowed "
                        "requests per minute/day" in context.exception)

    @mock.patch('soccer.writers.Stdout.live_scores')
    @mock.patch('requests.get')
    def test_get_live_scores_ok(self, mock_request_call, mock_writer):
        mock_request_call.side_effect = \
            [mocked_requests_get({'games': [1, 2]}, 200)]
        mock_writer.return_value = mock.Mock()
        self.rq.get_live_scores(True)
        mock_writer.assert_called_once()

    @mock.patch('click.secho')
    @mock.patch('soccer.writers.Stdout.live_scores')
    @mock.patch('requests.get')
    def test_get_live_scores_0_games(self,
                                     mock_request_call, mock_writer,
                                     mock_click):
        mock_request_call.side_effect = \
            [mocked_requests_get({'games': []}, 200)]
        mock_writer.return_value = mock.Mock()
        self.rq.get_live_scores(True)
        mock_click.assert_called_with("No live action "
                                      "currently", fg="red", bold=True)
        mock_writer.assert_called_once()

    @mock.patch('click.secho')
    @mock.patch('soccer.writers.Stdout.live_scores')
    @mock.patch('requests.get')
    def test_get_live_scores_error(self,
        mock_request_call, mock_writer, mock_click):
        mock_request_call.side_effect = \
            [mocked_requests_get({'games': [1, 2]}, 400)]
        mock_writer.return_value = mock.Mock()
        self.rq.get_live_scores(True)
        mock_click.assert_called_with("There was problem getting "
                                      "live scores", fg="red", bold=True)
        mock_writer.assert_called_once()

    @mock.patch('soccer.writers.Stdout.team_scores')
    @mock.patch('requests.get')
    def test_get_team_scores_ok(self,
                                mock_request_call, mock_writer):
        mock_request_call.side_effect = \
            [mocked_requests_get({'fixtures': [1, 2]}, 200)]
        mock_writer.return_value = mock.Mock()
        self.rq.get_team_scores(TestRequestHandler.VALID_TEAM_CODE,
                6, True, True)
        mock_writer.assert_called_once()

    @mock.patch('click.secho')
    @mock.patch('soccer.writers.Stdout.team_scores')
    @mock.patch('requests.get')
    def test_get_team_scores_0_fixtures(self,
                                        mock_request_call,
                                        mock_writer, mock_click):
        mock_request_call.side_effect = \
            [mocked_requests_get({'fixtures': []}, 200)]
        mock_writer.return_value = mock.Mock()
        self.rq.get_team_scores(TestRequestHandler.VALID_TEAM_CODE,
                6, True, True)
        mock_click.assert_called_with("No action during"
                                      " past week. Change the time "
                                      "parameter to get "
                                      "more fixtures.", fg="red", bold=True)
        mock_writer.assert_called_once()

    @mock.patch('click.secho')
    @mock.patch('soccer.writers.Stdout.team_scores')
    @mock.patch('requests.get')
    def test_get_team_scores_bad_id(self,
        mock_request_call, mock_writer, mock_click):
        mock_request_call.side_effect = \
            [mocked_requests_get({'fixtures': [1, 2]}, 200)]
        mock_writer.return_value = mock.Mock()
        self.rq.get_team_scores("AdkljdfkljkdlFC", 6, True, True)
        mock_click.assert_called_with("Team code is not "
                                      "correct.", fg="red", bold=True)
        mock_writer.assert_called_once()

    @mock.patch('click.secho')
    @mock.patch('requests.get')
    def test_get_standings_error(self,
        mock_request_call, mock_click):
        mock_request_call.side_effect = \
            APIErrorException()
        self.rq.get_standings(TestRequestHandler.VALID_LEAGUE_CODE)
        mock_click.assert_called_with("No standings availble for "
                "{league}.".format(
                    league=TestRequestHandler.VALID_LEAGUE_CODE),
                    fg="red", bold=True)

    @mock.patch('soccer.writers.Stdout.standings')
    @mock.patch('requests.get')
    def test_get_standings_ok(self,
                                    mock_request_call,
                                    mock_writer):
        mock_request_call.side_effect = \
            [mocked_requests_get({'standing': []}, 200)]
        mock_writer.return_value = mock.Mock()
        self.rq.get_standings(TestRequestHandler.VALID_LEAGUE_CODE)
        mock_writer.assert_called_once()

    @mock.patch('click.secho')
    @mock.patch('requests.get')
    def test_get_league_scores_error(self,
                                    mock_request_call,
                                    mock_click):
        mock_request_call.side_effect = \
            APIErrorException()
        self.rq.get_league_scores(TestRequestHandler.VALID_LEAGUE_CODE,
                TestRequestHandler.VALID_TIME, False, False)
        mock_click.assert_called_with("No data "
                "for the given league.", fg="red", bold=True)

    @mock.patch('click.secho')
    @mock.patch('requests.get')
    def test_get_league_scores_no_fixtures(self,
                                    mock_request_call,
                                    mock_click):
        mock_request_call.side_effect = \
            [mocked_requests_get({'fixtures': []}, 200)]
        self.rq.get_league_scores(TestRequestHandler.VALID_LEAGUE_CODE,
                TestRequestHandler.VALID_TIME, False, False)
        mock_click.assert_called_with("No {league} matches in "
                "the past week.".format(
                    league=TestRequestHandler.VALID_LEAGUE_CODE),
                fg="red", bold=True)

    @mock.patch('soccer.writers.Stdout.league_scores')
    @mock.patch('requests.get')
    def test_get_league_scores_multiple_fixtures(self,
                                    mock_request_call,
                                    mock_writer):
        mock_request_call.side_effect = \
            [mocked_requests_get({'fixtures': [1]}, 200)]
        mock_writer.return_value = mock.Mock()
        self.rq.get_league_scores(TestRequestHandler.VALID_LEAGUE_CODE,
                TestRequestHandler.VALID_TIME, False, False)
        mock_writer.assert_called_once()

    @mock.patch('click.secho')
    @mock.patch('requests.get')
    def test_get_team_players_error(self,
                                    mock_request_call,
                                    mock_click):
        mock_request_call.side_effect = APIErrorException()
        self.rq.get_team_players(TestRequestHandler.VALID_TEAM_CODE)
        mock_click.assert_called_with("No data for the team. "
                "Please check the team code.", bold=True, fg="red")

    @mock.patch('click.secho')
    @mock.patch('requests.get')
    def test_get_team_players_no_players(self,
                                    mock_request_call,
                                    mock_click):
        mock_request_call.side_effect = \
            [mocked_requests_get({'count': "0"}, 200)]
        self.rq.get_team_players(TestRequestHandler.VALID_TEAM_CODE)
        mock_click.assert_called_with("No players found "
                "for this team", fg="red", bold=True)

    @mock.patch('soccer.writers.Stdout.team_players')
    @mock.patch('requests.get')
    def test_get_team_players_no_players(self,
                                    mock_request_call,
                                    mock_writer):
        mock_request_call.side_effect = \
            [mocked_requests_get({'count': "1"}, 200)]
        mock_writer.return_value = mock.Mock()
        self.rq.get_team_players(TestRequestHandler.VALID_TEAM_CODE)
        mock_writer.assert_called_once()
예제 #3
0
파일: main.py 프로젝트: ram278/soccer-cli
def main(league, time, standings, team, live, use12hour, players,
         output_format, output_file, upcoming, lookup, listcodes, apikey):
    """
    A CLI for live and past football scores from various football leagues.

    League codes:

    \b
    - CL: Champions League
    - PL: England Premier League
    - EL1: England League One
    - ELC: England Championship
    - FL1: French Ligue 1
    - FL2: French Ligue 2
    - BL: German Bundesliga
    - BL2: 2. Bundesliga
    - SA: Serie A
    - DED: Eredivisie
    - PPL: Primeira Liga
    - PD: Primera Division
    - SD: Segunda Division
    """
    headers = {'X-Auth-Token': apikey}

    try:
        if output_format == 'stdout' and output_file:
            raise IncorrectParametersException(
                'Printing output to stdout and '
                'saving to a file are mutually exclusive')
        writer = get_writer(output_format, output_file)
        rh = RequestHandler(headers, LEAGUE_IDS, TEAM_NAMES, writer)

        if listcodes:
            list_team_codes()
            return

        if live:
            rh.get_live_scores(use12hour)
            return

        if standings:
            if not league:
                raise IncorrectParametersException(
                    'Please specify a league. '
                    'Example --standings --league=EPL')
            rh.get_standings(league)
            return

        if team:
            if lookup:
                map_team_id(team)
                return
            if players:
                rh.get_team_players(team)
                return
            else:
                rh.get_team_scores(team, time, upcoming, use12hour)
                return

        rh.get_league_scores(league, time, upcoming, use12hour)
    except IncorrectParametersException as e:
        click.secho(e.message, fg="red", bold=True)
예제 #4
0
class TestRequestHandler(unittest.TestCase):

    VALID_LEAGUE_CODE = "BL"
    VALID_TEAM_CODE = "AFC"
    VALID_TIME = 10

    def setUp(self):
        dummy_key = 12345678901234567890123456789012
        headers = {'X-Auth-Token': dummy_key}
        TEAM_DATA = get_team_data()["teams"]
        TEAM_NAMES = {team["code"]: team["id"] for team in TEAM_DATA}
        LEAGUE_IDS = leagueids.LEAGUE_IDS
        self.dummy_url = "http://some_url"
        writer = get_writer()
        self.rq = RequestHandler(headers, LEAGUE_IDS, TEAM_NAMES, writer)

    def tearDown(self):
        pass

    @mock.patch('requests.get')
    def test_ok_code(self, mock_call):
        mock_call.return_value = mock.MagicMock(status_code=requests.codes.ok,
                                                response=json.dumps(
                                                    {'key': 'value'}))
        try:
            self.rq._get(self.dummy_url)
        except APIErrorException:
            self.fail("Threw exception erroneously")

    @mock.patch('requests.get')
    def test_bad_code(self, mock_call):
        mock_call.return_value = mock.MagicMock(status_code=requests.codes.bad,
                                                response=json.dumps(
                                                    {'key': 'value'}))
        with self.assertRaises(APIErrorException) as context:
            self.rq._get(self.dummy_url)
        self.assertTrue("Invalid request. "
                        "Check parameters." in context.exception)

    @mock.patch('requests.get')
    def test_forbidden_code(self, mock_call):
        mock_call.return_value = mock.MagicMock(
            status_code=requests.codes.forbidden,
            response=json.dumps({'key': 'value'}))
        with self.assertRaises(APIErrorException) as context:
            self.rq._get(self.dummy_url)
        self.assertTrue('This resource is restricted' in context.exception)

    @mock.patch('requests.get')
    def test_not_found_code(self, mock_call):
        mock_call.return_value = mock.MagicMock(
            status_code=requests.codes.not_found,
            response=json.dumps({'key': 'value'}))
        with self.assertRaises(APIErrorException) as context:
            self.rq._get(self.dummy_url)
        self.assertTrue("This resource does not exist. "
                        "Check parameters" in context.exception)

    @mock.patch('requests.get')
    def test_too_many_requests_code(self, mock_call):
        mock_call.return_value = mock.MagicMock(
            status_code=requests.codes.too_many_requests,
            response=json.dumps({'key': 'value'}))
        with self.assertRaises(APIErrorException) as context:
            self.rq._get(self.dummy_url)
        self.assertTrue("You have exceeded your allowed "
                        "requests per minute/day" in context.exception)

#    @mock.patch('soccer.writers.Stdout.live_scores')
#    @mock.patch('requests.get')
#    def test_get_live_scores_ok(self, mock_request_call, mock_writer):
#        mock_request_call.side_effect = \
#            [mocked_requests_get({'games': [1, 2]}, 200)]
#        mock_writer.return_value = mock.Mock()
#        self.rq.get_live_scores(True)
#        mock_writer.assert_called_once()

    @mock.patch('click.secho')
    @mock.patch('soccer.writers.Stdout.live_scores')
    @mock.patch('requests.get')
    def test_get_live_scores_0_games(self, mock_request_call, mock_writer,
                                     mock_click):
        mock_request_call.side_effect = \
            [mocked_requests_get({'games': []}, 200)]
        mock_writer.return_value = mock.Mock()
        self.rq.get_live_scores(True)
        mock_click.assert_called_with("No live action "
                                      "currently",
                                      fg="red",
                                      bold=True)
        mock_writer.assert_called_once()

    @mock.patch('click.secho')
    @mock.patch('soccer.writers.Stdout.live_scores')
    @mock.patch('requests.get')
    def test_get_live_scores_error(self, mock_request_call, mock_writer,
                                   mock_click):
        mock_request_call.side_effect = \
            [mocked_requests_get({'games': [1, 2]}, 400)]
        mock_writer.return_value = mock.Mock()
        self.rq.get_live_scores(True)
        mock_click.assert_called_with(
            "There was problem getting "
            "live scores", fg="red", bold=True)
        mock_writer.assert_called_once()

#    @mock.patch('soccer.writers.Stdout.team_scores')
#    @mock.patch('requests.get')
#    def test_get_team_scores_ok(self,
#                                mock_request_call, mock_writer):
#        mock_request_call.side_effect = \
#            [mocked_requests_get({'fixtures': [1, 2]}, 200)]
#        mock_writer.return_value = mock.Mock()
#        self.rq.get_team_scores(TestRequestHandler.VALID_TEAM_CODE,
#                6, True, True)
#        mock_writer.assert_called_once()

#    @mock.patch('click.secho')
#    @mock.patch('soccer.writers.Stdout.team_scores')
#    @mock.patch('requests.get')
#    def test_get_team_scores_0_fixtures(self,
#                                        mock_request_call,
#                                        mock_writer, mock_click):
#        mock_request_call.side_effect = \
#            [mocked_requests_get({'fixtures': []}, 200)]
#        mock_writer.return_value = mock.Mock()
#        self.rq.get_team_scores(TestRequestHandler.VALID_TEAM_CODE,
#                6, True, True)
#        mock_click.assert_called_with("No action during"
#                                      " past week. Change the time "
#                                      "parameter to get "
#                                      "more fixtures.", fg="red", bold=True)
#        mock_writer.assert_called_once()

    @mock.patch('click.secho')
    @mock.patch('soccer.writers.Stdout.team_scores')
    @mock.patch('requests.get')
    def test_get_team_scores_bad_id(self, mock_request_call, mock_writer,
                                    mock_click):
        mock_request_call.side_effect = \
            [mocked_requests_get({'fixtures': [1, 2]}, 200)]
        mock_writer.return_value = mock.Mock()
        self.rq.get_team_scores("AdkljdfkljkdlFC", 6, True, True)
        mock_click.assert_called_with("Team code is not "
                                      "correct.",
                                      fg="red",
                                      bold=True)
        mock_writer.assert_called_once()

    @mock.patch('click.secho')
    @mock.patch('requests.get')
    def test_get_standings_error(self, mock_request_call, mock_click):
        mock_request_call.side_effect = \
            APIErrorException()
        self.rq.get_standings(TestRequestHandler.VALID_LEAGUE_CODE)
        mock_click.assert_called_with(
            "No standings availble for "
            "{league}.".format(league=TestRequestHandler.VALID_LEAGUE_CODE),
            fg="red",
            bold=True)

    @mock.patch('soccer.writers.Stdout.standings')
    @mock.patch('requests.get')
    def test_get_standings_ok(self, mock_request_call, mock_writer):
        mock_request_call.side_effect = \
            [mocked_requests_get({'standing': []}, 200)]
        mock_writer.return_value = mock.Mock()
        self.rq.get_standings(TestRequestHandler.VALID_LEAGUE_CODE)
        mock_writer.assert_called_once()

    @mock.patch('click.secho')
    @mock.patch('requests.get')
    def test_get_league_scores_error(self, mock_request_call, mock_click):
        mock_request_call.side_effect = \
            APIErrorException()
        self.rq.get_league_scores(TestRequestHandler.VALID_LEAGUE_CODE,
                                  TestRequestHandler.VALID_TIME, False, False)
        mock_click.assert_called_with("No data "
                                      "for the given league.",
                                      fg="red",
                                      bold=True)

#    @mock.patch('click.secho')
#    @mock.patch('requests.get')
#    def test_get_league_scores_no_fixtures(self,
#                                    mock_request_call,
#                                    mock_click):
#        mock_request_call.side_effect = \
#            [mocked_requests_get({'fixtures': []}, 200)]
#        self.rq.get_league_scores(TestRequestHandler.VALID_LEAGUE_CODE,
#                TestRequestHandler.VALID_TIME, False, False)
#        mock_click.assert_called_with("No {league} matches in "
#                "the past week.".format(
#                    league=TestRequestHandler.VALID_LEAGUE_CODE),
#                fg="red", bold=True)

#    @mock.patch('soccer.writers.Stdout.league_scores')
#    @mock.patch('requests.get')
#    def test_get_league_scores_multiple_fixtures(self,
#                                    mock_request_call,
#                                    mock_writer):
#        mock_request_call.side_effect = \
#            [mocked_requests_get({'fixtures': [1]}, 200)]
#        mock_writer.return_value = mock.Mock()
#        self.rq.get_league_scores(TestRequestHandler.VALID_LEAGUE_CODE,
#                TestRequestHandler.VALID_TIME, False, False)
#        mock_writer.assert_called_once()

    @mock.patch('click.secho')
    @mock.patch('requests.get')
    def test_get_team_players_error(self, mock_request_call, mock_click):
        mock_request_call.side_effect = APIErrorException()
        self.rq.get_team_players(TestRequestHandler.VALID_TEAM_CODE)
        mock_click.assert_called_with(
            "No data for the team. "
            "Please check the team code.",
            bold=True,
            fg="red")