コード例 #1
0
def main():
    #configFile = json.load(open('../config/soccer_data_config.json', 'r'))
    configFile = json.load(open('../config/config.json', 'r'))
    if not configFile:
        click.secho("Could not find configFile", fg="red", bold=True)
        exit(-1)
    
    apikey = configFile['apiToken']
    print("API Token found.")
    print(apikey)
    headers = {'X-Auth-Token': apikey}
    print("Fetching today's date ...")
    
    today = date.today()
    print("Today is: {}".format(today.strftime("%Y-%m-%d")))
    try:
        print("Instatiating request handler")
        rh = RequestHandler(headers)
        print("Instatiating json Writer and reader")
        js = JSonWR('../data/init')
        jsJOB = JSonWR('../data/updates')
        
        for competition in configFile['competitions']:
            print("Trying to fetch information on {}".format(competition['Name']))
            league = rh.get_league(competition['ID'])
            if not league:
                click.secho("League: {} with ID: {} NOT FOUND".format(competition['Name'], competition['ID']), fg="red", bold=True)
                continue

            js.save_json(league, ['league', str(league['id'])] )
            jsJOB.save_json(league, ['league', str(league['id'])])

            seasons = league['seasons'][:competition['seasons']]
            for season in seasons:
                teams = None
                if not os.path.isfile('../data/init/league_{}_season_{}_matches.json'.format(league['id'], season['startDate'][:4])):
                    teams = rh.get_teams_in_league(league, season = season)
                
                if teams:
                    print("Teams fetched for Season {}".format(teams['season']['startDate']))
                    js.save_json(teams, ['league', 
                                        str(league['id']), 
                                        'season', 
                                        season['startDate'][:4],
                                        'teams'] )
                else:
                    click.secho("NO NEW Teams for this league in this season: {}".format(competition['Name']), fg="red", bold=True) 

                matches = None
                if not os.path.isfile('../data/init/league_{}_season_{}_matches.json'.format(league['id'], season['startDate'][:4])):
                    matches = rh.get_league_scores(league, season = season, matchFilter = competition['matchFilter'])
                
                if matches:
                    print("Matches fetched: {} {}".format(len(matches['matches']), matches['count']))
                    js.save_json(matches, ['league', 
                                            str(league['id']), 
                                            'season', 
                                            season['startDate'][:4],
                                            'matches'] )   
                else:
                    click.secho("NO NEW matches for this season", fg="red", bold=True)             
                             
        
    except IncorrectParametersException as e:
        click.secho(str(e), fg="red", bold=True)
コード例 #2
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)
コード例 #3
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")
コード例 #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")

    @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()
コード例 #5
0
def main():
    tree_printer('..')
    configFile = json.load(open('../config/soccer_data_config.json', 'r'))
    if not configFile:
        click.secho("Could not find configFile", fg="red", bold=True)
        exit(-1)

    apikey = configFile['apiToken']
    print("API Token found.")
    print(apikey)
    headers = {'X-Auth-Token': apikey}
    print("Fetching today's date ...")

    today = date.today()
    print("Today is: {}".format(today.strftime("%Y-%m-%d")))
    try:
        print("Instatiating request handler")
        #NEED TO MAKE IT A THREAD
        rh = RequestHandler(headers)
        print("Instatiating json Writer and reader")
        js = JSonWR('../data/updates')

        for competition in configFile['competitions']:
            print("Trying to fetch information on {}".format(
                competition['Name']))
            league = rh.get_league(competition['ID'])
            if not league:
                click.secho("League: {} with ID: {} NOT FOUND".format(
                    competition['Name'], competition['ID']),
                            fg="red",
                            bold=True)
                break

            season = league['seasons'][0]
            new_season = False
            last_season_updated = js.open_json(['league',
                                                str(league['id'])
                                                ])['seasons'][0]
            if season != last_season_updated:
                new_season = True

            update_matches = rh.get_league_scores(
                league,
                matchFilter=competition['matchFilter'],
                dateFrom=(today - timedelta(days=1)),
                dateTo=datetime.strptime(season['endDate'], '%Y-%m-%d'))

            if new_season:
                update_teams = rh.get_teams_in_league(league, season=season)
                if update_teams:
                    print(
                        "New Season update available, teams fetched: ".format(
                            len(update_teams['teams'])))
                    js.save_json(update_teams, [
                        'league',
                        str(league['id']), 'season', season['startDate'][:4],
                        'updated_teams'
                    ])
            if update_matches:
                print("New Matches fetched: {}".format(
                    len(update_matches['matches'])))
                js.save_json(update_matches, [
                    'league',
                    str(league['id']), 'season', season['startDate'][:4],
                    'updated_matches',
                    today.strftime("%Y_%m_%d")
                ])
                js.save_json(league, ['league', str(league['id'])])
            else:
                click.secho("NO new matches for this week",
                            fg="red",
                            bold=True)

    except IncorrectParametersException as e:
        click.secho(str(e), fg="red", bold=True)