From fabd5ac0ea57b961937898bfc3bfbe3d49656996 Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Mon, 5 Dec 2016 11:31:56 +0100 Subject: [PATCH 01/71] trying to automate complexity checking --- .travis.yml | 1 + pytest.ini | 2 ++ travis_requirements.txt | 5 ++++- 3 files changed, 7 insertions(+), 1 deletion(-) create mode 100644 pytest.ini diff --git a/.travis.yml b/.travis.yml index dd05de9..70b58ad 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,6 +12,7 @@ install: script: - "./manage.py migrate" - coverage run --branch --source . manage.py test +- py.test --mccabe -m mccabe notifications: email: recipients: diff --git a/pytest.ini b/pytest.ini new file mode 100644 index 0000000..eaa1d6d --- /dev/null +++ b/pytest.ini @@ -0,0 +1,2 @@ +[pytest] +DJANGO_SETTINGS_MODULE=ofm_helper.settings.dev diff --git a/travis_requirements.txt b/travis_requirements.txt index d53eb39..5e7f42a 100644 --- a/travis_requirements.txt +++ b/travis_requirements.txt @@ -1 +1,4 @@ -pyvirtualdisplay==0.2 +pyvirtualdisplay +pytest +pytest-django +pytest-mccabe From aaf67fa997a29708e3f87e9bce0f513f83fd8c2c Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Mon, 5 Dec 2016 12:05:08 +0100 Subject: [PATCH 02/71] automate pyflakes and pep8 checking as well --- .travis.yml | 2 ++ pytest.ini | 1 + travis_requirements.txt | 2 ++ 3 files changed, 5 insertions(+) diff --git a/.travis.yml b/.travis.yml index 70b58ad..90c1afa 100644 --- a/.travis.yml +++ b/.travis.yml @@ -13,6 +13,8 @@ script: - "./manage.py migrate" - coverage run --branch --source . manage.py test - py.test --mccabe -m mccabe +- py.test --flakes +- py.test --pep8 notifications: email: recipients: diff --git a/pytest.ini b/pytest.ini index eaa1d6d..394bcdc 100644 --- a/pytest.ini +++ b/pytest.ini @@ -1,2 +1,3 @@ [pytest] DJANGO_SETTINGS_MODULE=ofm_helper.settings.dev +pep8ignore = E501 diff --git a/travis_requirements.txt b/travis_requirements.txt index 5e7f42a..100a10d 100644 --- a/travis_requirements.txt +++ b/travis_requirements.txt @@ -2,3 +2,5 @@ pyvirtualdisplay pytest pytest-django pytest-mccabe +pytest-flakes +pytest-pep8 From b115dec152cc74e341b4aa7a54fa5df38811a4a3 Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Mon, 5 Dec 2016 12:44:12 +0100 Subject: [PATCH 03/71] remove unused imports --- core/parsers/future_match_row_parser.py | 1 - core/parsers/stadium_stand_statistics_parser.py | 2 +- core/tests/unit/parser/test_stadium_statistics_parser.py | 4 ++-- core/tests/unit/views/test_checklist_settings_view.py | 4 ++-- core/tests/unit/views/test_ofm_stadium_detail_view.py | 7 ++----- .../unit/views/test_ofm_stadium_stand_statistics_view.py | 6 +++--- ofm_helper/urls.py | 2 -- 7 files changed, 10 insertions(+), 16 deletions(-) diff --git a/core/parsers/future_match_row_parser.py b/core/parsers/future_match_row_parser.py index 49df47e..94b4b0e 100644 --- a/core/parsers/future_match_row_parser.py +++ b/core/parsers/future_match_row_parser.py @@ -1,6 +1,5 @@ import logging -from bs4 import BeautifulSoup from django.core.exceptions import MultipleObjectsReturned from core.models import Matchday, Match, MatchTeamStatistics diff --git a/core/parsers/stadium_stand_statistics_parser.py b/core/parsers/stadium_stand_statistics_parser.py index b4d0708..c952510 100644 --- a/core/parsers/stadium_stand_statistics_parser.py +++ b/core/parsers/stadium_stand_statistics_parser.py @@ -2,7 +2,7 @@ from bs4 import BeautifulSoup -from core.models import Match, MatchStadiumStatistics, StadiumStandStatistics, StandLevel +from core.models import MatchStadiumStatistics, StadiumStandStatistics, StandLevel from core.parsers.base_parser import BaseParser logger = logging.getLogger(__name__) diff --git a/core/tests/unit/parser/test_stadium_statistics_parser.py b/core/tests/unit/parser/test_stadium_statistics_parser.py index 89bd3e6..58db580 100644 --- a/core/tests/unit/parser/test_stadium_statistics_parser.py +++ b/core/tests/unit/parser/test_stadium_statistics_parser.py @@ -2,9 +2,9 @@ from django.test import TestCase -from core.factories.core_factories import MatchFactory, StadiumLevelItemFactory, StadiumLevelFactory, \ +from core.factories.core_factories import MatchFactory, StadiumLevelFactory, \ MatchStadiumStatisticsFactory, MatchdayFactory -from core.models import MatchStadiumStatistics, StadiumLevel, StadiumLevelItem, Match +from core.models import MatchStadiumStatistics, StadiumLevel, StadiumLevelItem from core.parsers.stadium_statistics_parser import StadiumStatisticsParser from users.factories.users_factories import OFMUserFactory diff --git a/core/tests/unit/views/test_checklist_settings_view.py b/core/tests/unit/views/test_checklist_settings_view.py index bd5862f..a84209a 100644 --- a/core/tests/unit/views/test_checklist_settings_view.py +++ b/core/tests/unit/views/test_checklist_settings_view.py @@ -4,8 +4,8 @@ from django.test import TestCase from core.factories.core_factories import MatchdayFactory, ChecklistItemFactory, ChecklistFactory, MatchFactory, \ - FinanceFactory, MatchTeamStatisticsFactory -from core.models import ChecklistItem, Matchday, Match + FinanceFactory +from core.models import ChecklistItem from users.models import OFMUser diff --git a/core/tests/unit/views/test_ofm_stadium_detail_view.py b/core/tests/unit/views/test_ofm_stadium_detail_view.py index 1bf46d3..a10ab4a 100644 --- a/core/tests/unit/views/test_ofm_stadium_detail_view.py +++ b/core/tests/unit/views/test_ofm_stadium_detail_view.py @@ -1,10 +1,7 @@ -import json +from django.test import TestCase -from core.factories.core_factories import MatchdayFactory, PlayerFactory, PlayerStatisticsFactory, MatchFactory, \ +from core.factories.core_factories import MatchdayFactory, MatchFactory, \ MatchStadiumStatisticsFactory, StadiumStandStatisticsFactory -from core.models import Contract -from django.core.urlresolvers import reverse -from django.test import TestCase from users.models import OFMUser diff --git a/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py b/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py index 0e0d522..9194a94 100644 --- a/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py +++ b/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py @@ -1,10 +1,10 @@ import json -from core.factories.core_factories import MatchdayFactory, PlayerFactory, PlayerStatisticsFactory, MatchFactory, \ - MatchStadiumStatisticsFactory, StadiumStandStatisticsFactory -from core.models import Contract from django.core.urlresolvers import reverse from django.test import TestCase + +from core.factories.core_factories import MatchdayFactory, MatchFactory, \ + MatchStadiumStatisticsFactory, StadiumStandStatisticsFactory from users.models import OFMUser diff --git a/ofm_helper/urls.py b/ofm_helper/urls.py index 5d59462..626234f 100644 --- a/ofm_helper/urls.py +++ b/ofm_helper/urls.py @@ -1,5 +1,3 @@ -import django -from django.conf import settings from django.conf.urls import url, include from django.contrib import admin From 43e0e7663df5a7668492e2e093bf05c4219c994b Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Mon, 5 Dec 2016 13:20:32 +0100 Subject: [PATCH 04/71] ignore import star in settings files --- ofm_helper/settings/test.py | 6 +++++- pytest.ini | 2 ++ 2 files changed, 7 insertions(+), 1 deletion(-) diff --git a/ofm_helper/settings/test.py b/ofm_helper/settings/test.py index 1c43cda..a47ee53 100644 --- a/ofm_helper/settings/test.py +++ b/ofm_helper/settings/test.py @@ -2,4 +2,8 @@ DEBUG = True -USE_DISPLAY_FOR_AWS = True \ No newline at end of file +USE_DISPLAY_FOR_AWS = True + +ALLOWED_HOSTS = ['*'] + +LOGGING['loggers']['django']['handlers'] = ['file'] diff --git a/pytest.ini b/pytest.ini index 394bcdc..86cc7e2 100644 --- a/pytest.ini +++ b/pytest.ini @@ -1,3 +1,5 @@ [pytest] DJANGO_SETTINGS_MODULE=ofm_helper.settings.dev pep8ignore = E501 +flakes-ignore = + settings/*.py ImportStarUsage ImportStarUsed From 551495c5c92e04673245fbb7b204d1635ecdabf8 Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Mon, 5 Dec 2016 13:22:01 +0100 Subject: [PATCH 05/71] wrong copy paste error --- ofm_helper/settings/test.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ofm_helper/settings/test.py b/ofm_helper/settings/test.py index a47ee53..f109392 100644 --- a/ofm_helper/settings/test.py +++ b/ofm_helper/settings/test.py @@ -6,4 +6,4 @@ ALLOWED_HOSTS = ['*'] -LOGGING['loggers']['django']['handlers'] = ['file'] +LOGGING['loggers']['django']['handlers'] = ['console'] From 559b2d5140868c8bab83e402156668aba302954a Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Mon, 5 Dec 2016 13:44:57 +0100 Subject: [PATCH 06/71] fix all pep8 warnings + ignore some --- core/managers/parser_manager.py | 10 +- core/models.py | 25 +-- core/ofm_views.py | 154 ++++++++++-------- core/parsers/future_match_row_parser.py | 8 +- .../won_by_default_match_row_parser.py | 8 +- .../unit/parser/test_awp_boundaries_parser.py | 7 +- .../parser/test_future_match_row_parser.py | 1 - core/tests/unit/test_core_models.py | 5 +- .../views/test_ofm_finances_charts_views.py | 8 +- .../unit/views/test_ofm_finances_view.py | 18 +- .../unit/views/test_ofm_player_detail_view.py | 30 ++-- .../views/test_ofm_player_statistics_view.py | 30 ++-- .../views/test_ofm_stadium_detail_view.py | 12 +- .../test_ofm_stadium_stand_statistics_view.py | 8 +- core/tests/unit/views/test_parser_view.py | 6 +- ofm_helper/settings/docker.py | 16 +- pytest.ini | 2 +- users/tests/unit/test_user_models.py | 2 - 18 files changed, 192 insertions(+), 158 deletions(-) diff --git a/core/managers/parser_manager.py b/core/managers/parser_manager.py index 468ee07..17a7f39 100644 --- a/core/managers/parser_manager.py +++ b/core/managers/parser_manager.py @@ -37,12 +37,12 @@ def parse_ofm_version(self, site_manager): site_manager.jump_to_frame(Constants.GITHUB.LATEST_RELEASE) version_parser = OfmHelperVersionParser(site_manager.browser.page_source) return version_parser.parse() - + def parse_matchday(self, request, site_manager): site_manager.jump_to_frame(Constants.HEAD) matchday_parser = MatchdayParser(site_manager.browser.page_source) return matchday_parser.parse() - + def parse_players(self, request, site_manager): if not self.parsed_matchday: self.parsed_matchday = self.parse_matchday(request, site_manager) @@ -54,14 +54,16 @@ def parse_player_statistics(self, request, site_manager): if not self.players_already_parsed: self.parse_players(request, site_manager) site_manager.jump_to_frame(Constants.TEAM.PLAYER_STATISTICS) - player_stat_parser = PlayerStatisticsParser(site_manager.browser.page_source, request.user, self.parsed_matchday) + player_stat_parser = PlayerStatisticsParser(site_manager.browser.page_source, request.user, + self.parsed_matchday) return player_stat_parser.parse() def parse_awp_boundaries(self, request, site_manager): if not self.parsed_matchday: self.parsed_matchday = self.parse_matchday(request, site_manager) site_manager.jump_to_frame(Constants.AWP_BOUNDARIES) - awp_boundaries_parser = AwpBoundariesParser(site_manager.browser.page_source, request.user, self.parsed_matchday) + awp_boundaries_parser = AwpBoundariesParser(site_manager.browser.page_source, request.user, + self.parsed_matchday) return awp_boundaries_parser.parse() def parse_finances(self, request, site_manager): diff --git a/core/models.py b/core/models.py index e0d2126..b03b6db 100644 --- a/core/models.py +++ b/core/models.py @@ -483,6 +483,7 @@ def __str__(self): class StadiumLevelItem(models.Model): class Meta: ordering = ['-current_level', '-value', '-daily_costs'] + current_level = models.IntegerField(default=0) value = models.IntegerField(default=0) daily_costs = models.IntegerField(default=0) @@ -498,7 +499,8 @@ class StadiumLevel(models.Model): parking = models.ForeignKey(StadiumLevelItem, related_name="stadium_levels_parking") def __str__(self): - return "light: %s / screen: %s / security: %s / parking: %s" % (self.light, self.screen, self.security, self.parking) + return "light: %s / screen: %s / security: %s / parking: %s" % ( + self.light, self.screen, self.security, self.parking) # will only be created, if home match @@ -514,11 +516,8 @@ def get_absolute_url(self): return reverse('core:ofm:stadium_detail', args=[str(self.id)]) def get_configuration(self): - config = {} - config['light'] = self.level.light.current_level - config['screen'] = self.level.screen.current_level - config['security'] = self.level.security.current_level - config['parking'] = self.level.parking.current_level + config = {'light': self.level.light.current_level, 'screen': self.level.screen.current_level, + 'security': self.level.security.current_level, 'parking': self.level.parking.current_level} north_stand = StadiumStandStatistics.objects.filter(stadium_statistics=self, sector='N') south_stand = StadiumStandStatistics.objects.filter(stadium_statistics=self, sector='S') @@ -541,11 +540,13 @@ def get_configuration(self): @property def visitors(self): - return StadiumStandStatistics.objects.filter(stadium_statistics=self).aggregate(Sum('visitors'))['visitors__sum'] + return StadiumStandStatistics.objects.filter(stadium_statistics=self).aggregate(Sum('visitors'))[ + 'visitors__sum'] @property def capacity(self): - return StadiumStandStatistics.objects.filter(stadium_statistics=self).aggregate(Sum('level__capacity'))['level__capacity__sum'] + return StadiumStandStatistics.objects.filter(stadium_statistics=self).aggregate(Sum('level__capacity'))[ + 'level__capacity__sum'] @property def earnings(self): @@ -556,7 +557,8 @@ def earnings(self): @property def daily_costs(self): - return self.level.light.daily_costs + self.level.screen.daily_costs + self.level.security.daily_costs + self.level.parking.daily_costs + return self.level.light.daily_costs + self.level.screen.daily_costs + \ + self.level.security.daily_costs + self.level.parking.daily_costs def __str__(self): return "%s (%s)" % (self.match.venue, self.match.matchday) @@ -774,7 +776,7 @@ def get_from_matchday(matchday): except Dictionary.DoesNotExist: awp_boundaries = AwpBoundaries.get_or_create_from_matchday(matchday) for i in range(26): - awp_boundaries[i+1] = 0 + awp_boundaries[i + 1] = 0 return awp_boundaries @staticmethod @@ -801,6 +803,7 @@ class Meta: name = models.CharField(max_length=255) priority = models.IntegerField(default=0) last_checked_on_matchday = models.ForeignKey(Matchday, default=None, blank=True, null=True) - to_be_checked_on_matchdays = models.CharField(blank=True, null=True, max_length=255, validators=[validate_comma_separated_integer_list]) + to_be_checked_on_matchdays = models.CharField(blank=True, null=True, max_length=255, + validators=[validate_comma_separated_integer_list]) to_be_checked_on_matchday_pattern = models.IntegerField(blank=True, null=True) to_be_checked_if_home_match_tomorrow = models.BooleanField(default=False) diff --git a/core/ofm_views.py b/core/ofm_views.py index 7e16265..ef14ad5 100644 --- a/core/ofm_views.py +++ b/core/ofm_views.py @@ -12,11 +12,11 @@ def _validate_filtered_field(field): - if len(field) > 1: - raise MultipleObjectsReturned - elif field: - field = field[0] - return field + if len(field) > 1: + raise MultipleObjectsReturned + elif field: + field = field[0] + return field @method_decorator(login_required, name='dispatch') @@ -35,7 +35,6 @@ def get_context_data(self, **kwargs): @method_decorator(login_required, name='dispatch') class PlayerStatisticsAsJsonView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): contracts = Contract.objects.filter(user=self.request.user, sold_on_matchday=None) players = [contract.player for contract in contracts] @@ -51,13 +50,16 @@ def get(self, request, *args, **kwargs): player_statistics_tuples = [] for player in players: newer_player_statistics, older_player_statistics = self._get_statistics_from_player_and_matchday(player, - newer_matchday_season, newer_matchday, - older_matchday_season, older_matchday) + newer_matchday_season, + newer_matchday, + older_matchday_season, + older_matchday) if newer_player_statistics and (older_player_statistics or not diff_mode_enabled): player_statistics_tuples.append((newer_player_statistics, older_player_statistics)) - player_statistics_json = [self._get_player_statistics_diff_in_json(newer_player_statistics, older_player_statistics) - for (newer_player_statistics, older_player_statistics) in player_statistics_tuples] + player_statistics_json = [ + self._get_player_statistics_diff_in_json(newer_player_statistics, older_player_statistics) + for (newer_player_statistics, older_player_statistics) in player_statistics_tuples] return self.render_json_response(player_statistics_json) @@ -65,14 +67,20 @@ def _get_statistics_from_player_and_matchday(self, player, newer_matchday_season, newer_matchday, older_matchday_season, older_matchday): - newer_player_statistics = PlayerStatistics.objects.filter(player=player, matchday__season__number=newer_matchday_season, matchday__number=newer_matchday) - older_player_statistics = PlayerStatistics.objects.filter(player=player, matchday__season__number=older_matchday_season, matchday__number=older_matchday) + newer_player_statistics = PlayerStatistics.objects.filter(player=player, + matchday__season__number=newer_matchday_season, + matchday__number=newer_matchday) + older_player_statistics = PlayerStatistics.objects.filter(player=player, + matchday__season__number=older_matchday_season, + matchday__number=older_matchday) newer_player_statistics = _validate_filtered_field(newer_player_statistics) older_player_statistics = _validate_filtered_field(older_player_statistics) if not newer_player_statistics: - newer_player_statistics = PlayerStatistics.objects.filter(player=player, matchday__season__number=newer_matchday_season).order_by('matchday')[0] + newer_player_statistics = \ + PlayerStatistics.objects.filter(player=player, matchday__season__number=newer_matchday_season).order_by( + 'matchday')[0] return newer_player_statistics, older_player_statistics @@ -109,7 +117,8 @@ def _get_player_statistics_diff_in_json(self, newer_player_statistics, older_pla statistic_diff['position'] = newer_player_statistics.player.position statistic_diff['age'] = newer_player_statistics.age statistic_diff['strength'] = strength - statistic_diff['name'] = '%s' % (newer_player_statistics.player.get_absolute_url(), newer_player_statistics.player.name) + statistic_diff['name'] = '%s' % ( + newer_player_statistics.player.get_absolute_url(), newer_player_statistics.player.name) statistic_diff['ep'] = ep statistic_diff['tp'] = tp statistic_diff['awp'] = awp @@ -160,7 +169,6 @@ def get_object(self, **kwargs): @method_decorator(login_required, name='dispatch') class PlayerChartView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): current_season_number = Matchday.objects.all()[0].season.number season_number = self.request.GET.get('season_number', default=current_season_number) @@ -206,15 +214,17 @@ def get_context_data(self, **kwargs): @method_decorator(login_required, name='dispatch') class FinancesAsJsonView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): - newer_matchday_season = self.request.GET.get('newer_matchday_season', default=Matchday.objects.all()[0].season.number) + newer_matchday_season = self.request.GET.get('newer_matchday_season', + default=Matchday.objects.all()[0].season.number) newer_matchday = self.request.GET.get('newer_matchday', default=Matchday.objects.all()[0].number) older_matchday_season = self.request.GET.get('older_matchday_season') older_matchday = self.request.GET.get('older_matchday') - newer_finances = Finance.objects.filter(user=request.user, matchday__season__number=newer_matchday_season, matchday__number=newer_matchday) - older_finances = Finance.objects.filter(user=request.user, matchday__season__number=older_matchday_season, matchday__number=older_matchday) + newer_finances = Finance.objects.filter(user=request.user, matchday__season__number=newer_matchday_season, + matchday__number=newer_matchday) + older_finances = Finance.objects.filter(user=request.user, matchday__season__number=older_matchday_season, + matchday__number=older_matchday) newer_finances = _validate_filtered_field(newer_finances) older_finances = _validate_filtered_field(older_finances) @@ -280,7 +290,8 @@ def _get_finances_diff_in_json(self, newer_finances, older_finances): expenses_player_salaries = -newer_finances.expenses_player_salaries if older_finances: - expenses_player_salaries = -(newer_finances.expenses_player_salaries - older_finances.expenses_player_salaries) + expenses_player_salaries = -( + newer_finances.expenses_player_salaries - older_finances.expenses_player_salaries) expenses_stadium = -newer_finances.expenses_stadium if older_finances: @@ -358,7 +369,6 @@ def _get_finances_diff_in_json(self, newer_finances, older_finances): @method_decorator(login_required, name='dispatch') class FinanceBalanceChartView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): current_season_number = Matchday.objects.all()[0].season.number season_number = self.request.GET.get('season_number', default=current_season_number) @@ -377,7 +387,6 @@ def get(self, request, *args, **kwargs): @method_decorator(login_required, name='dispatch') class FinanceIncomeChartView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): current_season_number = Matchday.objects.all()[0].season.number season_number = self.request.GET.get('season_number', default=current_season_number) @@ -409,18 +418,20 @@ def get(self, request, *args, **kwargs): matchdays.append(data_source[0].matchday.number) for idx, entry in enumerate(data_source): - if idx+1 < data_source.count(): - income_visitors_league.append(data_source[idx+1].income_visitors_league - data_source[idx].income_visitors_league) - income_sponsoring.append(data_source[idx+1].income_sponsoring - data_source[idx].income_sponsoring) - income_cup.append(data_source[idx+1].income_cup - data_source[idx].income_cup) - income_interests.append(data_source[idx+1].income_interests - data_source[idx].income_interests) - income_loan.append(data_source[idx+1].income_loan - data_source[idx].income_loan) - income_transfer.append(data_source[idx+1].income_transfer - data_source[idx].income_transfer) - income_visitors_friendlies.append(data_source[idx+1].income_visitors_friendlies - data_source[idx].income_visitors_friendlies) - income_friendlies.append(data_source[idx+1].income_friendlies - data_source[idx].income_friendlies) - income_funcup.append(data_source[idx+1].income_funcup - data_source[idx].income_funcup) - income_betting.append(data_source[idx+1].income_betting - data_source[idx].income_betting) - matchdays.append(data_source[idx+1].matchday.number) + if idx + 1 < data_source.count(): + income_visitors_league.append( + data_source[idx + 1].income_visitors_league - data_source[idx].income_visitors_league) + income_sponsoring.append(data_source[idx + 1].income_sponsoring - data_source[idx].income_sponsoring) + income_cup.append(data_source[idx + 1].income_cup - data_source[idx].income_cup) + income_interests.append(data_source[idx + 1].income_interests - data_source[idx].income_interests) + income_loan.append(data_source[idx + 1].income_loan - data_source[idx].income_loan) + income_transfer.append(data_source[idx + 1].income_transfer - data_source[idx].income_transfer) + income_visitors_friendlies.append( + data_source[idx + 1].income_visitors_friendlies - data_source[idx].income_visitors_friendlies) + income_friendlies.append(data_source[idx + 1].income_friendlies - data_source[idx].income_friendlies) + income_funcup.append(data_source[idx + 1].income_funcup - data_source[idx].income_funcup) + income_betting.append(data_source[idx + 1].income_betting - data_source[idx].income_betting) + matchdays.append(data_source[idx + 1].matchday.number) series = [] if sum(income_visitors_league) is not 0: @@ -454,7 +465,6 @@ def get(self, request, *args, **kwargs): @method_decorator(login_required, name='dispatch') class FinanceExpensesChartView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): current_season_number = Matchday.objects.all()[0].season.number season_number = self.request.GET.get('season_number', default=current_season_number) @@ -486,18 +496,21 @@ def get(self, request, *args, **kwargs): matchdays.append(data_source[0].matchday.number) for idx, entry in enumerate(data_source): - if idx+1 < data_source.count(): - expenses_player_salaries.append(data_source[idx].expenses_player_salaries - data_source[idx+1].expenses_player_salaries) - expenses_stadium.append(data_source[idx].expenses_stadium - data_source[idx+1].expenses_stadium) - expenses_youth.append(data_source[idx].expenses_youth - data_source[idx+1].expenses_youth) - expenses_interests.append(data_source[idx].expenses_interests - data_source[idx+1].expenses_interests) - expenses_trainings.append(data_source[idx].expenses_trainings - data_source[idx+1].expenses_trainings) - expenses_transfer.append(data_source[idx].expenses_transfer - data_source[idx+1].expenses_transfer) - expenses_compensation.append(data_source[idx].expenses_compensation - data_source[idx+1].expenses_compensation) - expenses_friendlies.append(data_source[idx].expenses_friendlies - data_source[idx+1].expenses_friendlies) - expenses_funcup.append(data_source[idx].expenses_funcup - data_source[idx+1].expenses_funcup) - expenses_betting.append(data_source[idx].expenses_betting - data_source[idx+1].expenses_betting) - matchdays.append(data_source[idx+1].matchday.number) + if idx + 1 < data_source.count(): + expenses_player_salaries.append( + data_source[idx].expenses_player_salaries - data_source[idx + 1].expenses_player_salaries) + expenses_stadium.append(data_source[idx].expenses_stadium - data_source[idx + 1].expenses_stadium) + expenses_youth.append(data_source[idx].expenses_youth - data_source[idx + 1].expenses_youth) + expenses_interests.append(data_source[idx].expenses_interests - data_source[idx + 1].expenses_interests) + expenses_trainings.append(data_source[idx].expenses_trainings - data_source[idx + 1].expenses_trainings) + expenses_transfer.append(data_source[idx].expenses_transfer - data_source[idx + 1].expenses_transfer) + expenses_compensation.append( + data_source[idx].expenses_compensation - data_source[idx + 1].expenses_compensation) + expenses_friendlies.append( + data_source[idx].expenses_friendlies - data_source[idx + 1].expenses_friendlies) + expenses_funcup.append(data_source[idx].expenses_funcup - data_source[idx + 1].expenses_funcup) + expenses_betting.append(data_source[idx].expenses_betting - data_source[idx + 1].expenses_betting) + matchdays.append(data_source[idx + 1].matchday.number) series = [] if sum(expenses_player_salaries) is not 0: @@ -546,7 +559,6 @@ def get_context_data(self, **kwargs): @method_decorator(login_required, name='dispatch') class MatchesAsJsonView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): season = self.request.GET.get('season', default=Matchday.objects.all()[0].season.number) matches = Match.objects.filter(user=self.request.user, matchday__season__number=season) @@ -617,13 +629,15 @@ def _get_match_in_json(self, match): @method_decorator(login_required, name='dispatch') class MatchesSummaryJsonView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): current_season = Matchday.objects.all()[0].season season_number = self.request.GET.get('season_number', current_season.number) - matches_won = len([match for match in Match.objects.filter(matchday__season__number=season_number) if match.is_won]) - matches_draw = len([match for match in Match.objects.filter(matchday__season__number=season_number) if match.is_draw]) - matches_lost = len([match for match in Match.objects.filter(matchday__season__number=season_number) if match.is_lost]) + matches_won = len( + [match for match in Match.objects.filter(matchday__season__number=season_number) if match.is_won]) + matches_draw = len( + [match for match in Match.objects.filter(matchday__season__number=season_number) if match.is_draw]) + matches_lost = len( + [match for match in Match.objects.filter(matchday__season__number=season_number) if match.is_lost]) json = { "matches_won": matches_won, @@ -645,12 +659,15 @@ def get_context_data(self, **kwargs): seasons = set(m.season.number for m in matchdays) tolerance = 5 - if self.request.COOKIES.get('slider_min') and self.request.COOKIES.get('slider_max') and self.request.COOKIES.get('tolerance'): + if self.request.COOKIES.get('slider_min') and \ + self.request.COOKIES.get('slider_max') and \ + self.request.COOKIES.get('tolerance'): slider_min = self.request.COOKIES['slider_min'] slider_max = self.request.COOKIES['slider_max'] tolerance = self.request.COOKIES['tolerance'] elif Match.objects.count() > 0: - match = Match.objects.filter(user=self.request.user, is_home_match=True).order_by('matchday')[0] # latest home match + match = Match.objects.filter(user=self.request.user, is_home_match=True).order_by('matchday')[ + 0] # latest home match slider_min = int(min(match.home_team_statistics.strength, match.guest_team_statistics.strength)) slider_max = int(max(match.home_team_statistics.strength, match.guest_team_statistics.strength)) else: @@ -674,11 +691,11 @@ def get_context_data(self, **kwargs): @method_decorator(login_required, name='dispatch') class StadiumStatisticsAsJsonView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): harmonic_strength = 150 tolerance = 5 - if self.request.COOKIES.get('slider_min') and self.request.COOKIES.get('slider_max') and self.request.COOKIES.get('tolerance'): + if self.request.COOKIES.get('slider_min') and self.request.COOKIES.get( + 'slider_max') and self.request.COOKIES.get('tolerance'): slider_min = int(self.request.COOKIES['slider_min']) slider_max = int(self.request.COOKIES['slider_max']) tolerance = int(self.request.COOKIES['tolerance']) @@ -727,12 +744,14 @@ def _get_stadium_statistics_in_json(self, stadium_stat): match_stadium_stat = dict() match_stadium_stat['season'] = stadium_stat.match.matchday.season.number - match_stadium_stat['matchday'] = "" + str(stadium_stat.match.matchday.number) + "" + match_stadium_stat['matchday'] = "" + str( + stadium_stat.match.matchday.number) + "" if stadium_stat.visitors and stadium_stat.capacity: match_stadium_stat['visitors'] = stadium_stat.visitors match_stadium_stat['capacity'] = stadium_stat.capacity match_stadium_stat['earnings'] = stadium_stat.earnings - match_stadium_stat['workload'] = locale.format("%.2f", stadium_stat.visitors / stadium_stat.capacity * 100) + " %" + match_stadium_stat['workload'] = locale.format("%.2f", + stadium_stat.visitors / stadium_stat.capacity * 100) + " %" else: # all stadium stands were under construction during match match_stadium_stat['visitors'] = 0 @@ -752,10 +771,15 @@ def _get_stadium_statistics_in_json(self, stadium_stat): match_stadium_stat['guest_strength'] = locale.format("%.1f", guest_strength) harmonic_strength = 2 * home_strength * guest_strength / (home_strength + guest_strength) match_stadium_stat['harmonic_strength'] = locale.format("%.1f", harmonic_strength) - match_stadium_stat['light_level'] = str(stadium_stat.level.light.current_level) + " (" + str(stadium_stat.level.light.value) + " €) " + str(stadium_stat.level.light.daily_costs) + " €" - match_stadium_stat['screen_level'] = str(stadium_stat.level.screen.current_level) + " (" + str(stadium_stat.level.screen.value) + " €) " + str(stadium_stat.level.screen.daily_costs) + " €" - match_stadium_stat['security_level'] = str(stadium_stat.level.security.current_level) + " (" + str(stadium_stat.level.security.value) + " €) " + str(stadium_stat.level.security.daily_costs) + " €" - match_stadium_stat['parking_level'] = str(stadium_stat.level.parking.current_level) + " (" + str(stadium_stat.level.parking.value) + " €) " + str(stadium_stat.level.parking.daily_costs) + " €" + match_stadium_stat['light_level'] = str(stadium_stat.level.light.current_level) + " (" + str( + stadium_stat.level.light.value) + " €) " + str(stadium_stat.level.light.daily_costs) + " €" + match_stadium_stat['screen_level'] = str(stadium_stat.level.screen.current_level) + " (" + str( + stadium_stat.level.screen.value) + " €) " + str(stadium_stat.level.screen.daily_costs) + " €" + match_stadium_stat['security_level'] = str(stadium_stat.level.security.current_level) + " (" + str( + stadium_stat.level.security.value) + " €) " + str( + stadium_stat.level.security.daily_costs) + " €" + match_stadium_stat['parking_level'] = str(stadium_stat.level.parking.current_level) + " (" + str( + stadium_stat.level.parking.value) + " €) " + str(stadium_stat.level.parking.daily_costs) + " €" return match_stadium_stat @@ -804,7 +828,8 @@ def get_context_data(self, **kwargs): seasons = [] sectors = [] - statistics = StadiumStandStatistics.objects.filter(stadium_statistics__match__user=self.request.user).order_by('stadium_statistics__match__matchday') + statistics = StadiumStandStatistics.objects.filter(stadium_statistics__match__user=self.request.user).order_by( + 'stadium_statistics__match__matchday') for stat in statistics: if stat.stadium_statistics.match.matchday.season not in seasons: seasons.append(stat.stadium_statistics.match.matchday.season) @@ -824,7 +849,6 @@ def get_context_data(self, **kwargs): @method_decorator(login_required, name='dispatch') class StadiumStandStatisticsChartView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): current_season_number = Matchday.objects.all()[0].season.number season_number = self.request.GET.get('season_number', default=current_season_number) @@ -852,7 +876,7 @@ def get(self, request, *args, **kwargs): "yAxis": 1 }, { "name": 'Gemittelte Stärke der Mannschaften', - "data": [float("{0:.2f}".format(s.stadium_statistics.match.harmonic_strength)) for s in statistics], + "data": [float("{0:.2f}".format(s.stadium_statistics.match.harmonic_strength)) for s in statistics], "yAxis": 1 }], "categories": [s.stadium_statistics.match.matchday.number for s in statistics], diff --git a/core/parsers/future_match_row_parser.py b/core/parsers/future_match_row_parser.py index 94b4b0e..f4fd598 100644 --- a/core/parsers/future_match_row_parser.py +++ b/core/parsers/future_match_row_parser.py @@ -31,12 +31,12 @@ def parse_html(self, row): is_home_match = "black" in row.find_all('td')[1].a.get('class') home_team = row.find_all('td')[1].get_text().strip() - home_team_name = home_team[0:home_team.find('(')-1] - home_team_strength = home_team[home_team.find('(')+1:home_team.find(')')] + home_team_name = home_team[0:home_team.find('(') - 1] + home_team_strength = home_team[home_team.find('(') + 1:home_team.find(')')] guest_team = row.find_all('td')[3].get_text().strip() - guest_team_name = guest_team[0:guest_team.find('(')-1] - guest_team_strength = guest_team[guest_team.find('(')+1:guest_team.find(')')] + guest_team_name = guest_team[0:guest_team.find('(') - 1] + guest_team_strength = guest_team[guest_team.find('(') + 1:guest_team.find(')')] existing_match = Match.objects.filter(matchday=matchday, user=self.user) diff --git a/core/parsers/won_by_default_match_row_parser.py b/core/parsers/won_by_default_match_row_parser.py index 0b64a79..f470dea 100644 --- a/core/parsers/won_by_default_match_row_parser.py +++ b/core/parsers/won_by_default_match_row_parser.py @@ -35,12 +35,12 @@ def parse_html(self, row): guest_team_score = match_result.split(':')[1].strip() home_team = row.find_all('td')[1].get_text().strip() - home_team_name = home_team[0:home_team.find('(')-1] - home_team_strength = home_team[home_team.find('(')+1:home_team.find(')')] + home_team_name = home_team[0:home_team.find('(') - 1] + home_team_strength = home_team[home_team.find('(') + 1:home_team.find(')')] guest_team = row.find_all('td')[3].get_text().strip() - guest_team_name = guest_team[0:guest_team.find('(')-1] - guest_team_strength = guest_team[guest_team.find('(')+1:guest_team.find(')')] + guest_team_name = guest_team[0:guest_team.find('(') - 1] + guest_team_strength = guest_team[guest_team.find('(') + 1:guest_team.find(')')] existing_match = Match.objects.filter(matchday=matchday, user=self.user) diff --git a/core/tests/unit/parser/test_awp_boundaries_parser.py b/core/tests/unit/parser/test_awp_boundaries_parser.py index a0763f0..2850719 100644 --- a/core/tests/unit/parser/test_awp_boundaries_parser.py +++ b/core/tests/unit/parser/test_awp_boundaries_parser.py @@ -51,15 +51,16 @@ def test_parser(self): def test_parser_does_not_create_new_boundaries_object_if_already_exists_for_quarter(self): self.matchday = MatchdayFactory.create(number=2) - self.parser = AwpBoundariesParser(open(os.path.join(TESTDATA_PATH, 'awp_boundaries.html'), encoding='utf8'), self.user, self.matchday) + self.parser = AwpBoundariesParser(open(os.path.join(TESTDATA_PATH, 'awp_boundaries.html'), encoding='utf8'), + self.user, self.matchday) self.parser.parse() self.assertEquals(AwpBoundaries.objects.count(), 1) def test_parser_creates_new_boundaries_object(self): self.matchday = MatchdayFactory.create(number=17) - self.parser = AwpBoundariesParser(open(os.path.join(TESTDATA_PATH, 'awp_boundaries.html'), encoding='utf8'), self.user, self.matchday) + self.parser = AwpBoundariesParser(open(os.path.join(TESTDATA_PATH, 'awp_boundaries.html'), encoding='utf8'), + self.user, self.matchday) self.parser.parse() self.assertEquals(AwpBoundaries.objects.count(), 2) - diff --git a/core/tests/unit/parser/test_future_match_row_parser.py b/core/tests/unit/parser/test_future_match_row_parser.py index f10dff1..a24b814 100644 --- a/core/tests/unit/parser/test_future_match_row_parser.py +++ b/core/tests/unit/parser/test_future_match_row_parser.py @@ -64,4 +64,3 @@ def test_match_gets_updated_on_parsing_again(self): self.assertEquals(match_stat2.home_team_statistics.strength, '61') self.assertEquals(match_stat2.guest_team_statistics.strength, '29') self.assertEquals(2, MatchTeamStatistics.objects.all().count()) - diff --git a/core/tests/unit/test_core_models.py b/core/tests/unit/test_core_models.py index 6d2b9d6..c057221 100644 --- a/core/tests/unit/test_core_models.py +++ b/core/tests/unit/test_core_models.py @@ -48,7 +48,8 @@ def test_get_current_matchday_from_player_statistics(self): self.assertEqual(Matchday.get_current(), m3) def test_get_current_matchday_from_matches(self): - user2 = OFMUser.objects.create_user('second', 'second@ofmhelper.com', 'second', ofm_username="second", ofm_password="second") + user2 = OFMUser.objects.create_user('second', 'second@ofmhelper.com', 'second', ofm_username="second", + ofm_password="second") MatchdayFactory.create(number=1) m2 = MatchdayFactory.create(number=5) m3 = MatchdayFactory.create(number=7) @@ -197,5 +198,3 @@ def test_create_checklist_item(self): self.assertTrue(cli.to_be_checked_on_matchdays is None) self.assertTrue(cli.to_be_checked_on_matchday_pattern is None) self.assertFalse(cli.to_be_checked_if_home_match_tomorrow) - - diff --git a/core/tests/unit/views/test_ofm_finances_charts_views.py b/core/tests/unit/views/test_ofm_finances_charts_views.py index 6684a55..0434a8c 100644 --- a/core/tests/unit/views/test_ofm_finances_charts_views.py +++ b/core/tests/unit/views/test_ofm_finances_charts_views.py @@ -11,9 +11,11 @@ class OFMFinancesViewTestCase(TestCase): def setUp(self): self.matchday = MatchdayFactory.create() self.next_matchday = MatchdayFactory.create(number=1) - self.user1 = OFMUser.objects.create_user(username='alice', email='alice@ofmhelper.com', password='alice', ofm_username='alice', ofm_password='alice') + self.user1 = OFMUser.objects.create_user(username='alice', email='alice@ofmhelper.com', password='alice', + ofm_username='alice', ofm_password='alice') self.finances = FinanceFactory.create(user=self.user1, matchday=self.matchday) - self.next_finances = FinanceFactory.create(user=self.user1, matchday=self.next_matchday, balance=2000, income_visitors_league=200, expenses_player_salaries=200) + self.next_finances = FinanceFactory.create(user=self.user1, matchday=self.next_matchday, balance=2000, + income_visitors_league=200, expenses_player_salaries=200) self.client.login(username='alice', password='alice') def test_finance_balance_chart_json(self): @@ -42,5 +44,3 @@ def test_finance_expenses_chart_json(self): self.assertEquals('Spielergehalt', returned_json_data['series'][0]['name']) self.assertTrue('data' in returned_json_data['series'][0]) self.assertTrue('categories' in returned_json_data) - - diff --git a/core/tests/unit/views/test_ofm_finances_view.py b/core/tests/unit/views/test_ofm_finances_view.py index 712053b..9602af7 100644 --- a/core/tests/unit/views/test_ofm_finances_view.py +++ b/core/tests/unit/views/test_ofm_finances_view.py @@ -11,9 +11,11 @@ class OFMFinancesViewTestCase(TestCase): def setUp(self): self.matchday = MatchdayFactory.create() self.next_matchday = MatchdayFactory.create(number=1) - self.user1 = OFMUser.objects.create_user(username='alice', email='alice@ofmhelper.com', password='alice', ofm_username='alice', ofm_password='alice') + self.user1 = OFMUser.objects.create_user(username='alice', email='alice@ofmhelper.com', password='alice', + ofm_username='alice', ofm_password='alice') self.finances = FinanceFactory.create(user=self.user1, matchday=self.matchday) - self.next_finances = FinanceFactory.create(user=self.user1, matchday=self.next_matchday, balance=2000, income_visitors_league=200, expenses_player_salaries=200) + self.next_finances = FinanceFactory.create(user=self.user1, matchday=self.next_matchday, balance=2000, + income_visitors_league=200, expenses_player_salaries=200) self.client.login(username='alice', password='alice') def test_user_can_see_his_finances(self): @@ -39,8 +41,9 @@ def test_user_can_see_his_latest_finances_when_given_no_matchday(self): self.assertEquals(returned_json_data[0]['expenses_player_salaries'], -200) def test_user_can_see_his_finances_diff_when_given_both_matchdays(self): - third_matchday = MatchdayFactory.create(number=self.matchday.number+2) - FinanceFactory.create(user=self.user1, matchday=third_matchday, balance=2500, income_visitors_league=250, income_sponsoring=250, expenses_player_salaries=250, expenses_youth=100) + third_matchday = MatchdayFactory.create(number=self.matchday.number + 2) + FinanceFactory.create(user=self.user1, matchday=third_matchday, balance=2500, income_visitors_league=250, + income_sponsoring=250, expenses_player_salaries=250, expenses_youth=100) response = self.client.get(reverse('core:ofm:finances_json'), {'newer_matchday_season': third_matchday.season.number, @@ -60,13 +63,14 @@ def test_user_can_see_his_finances_diff_when_given_both_matchdays(self): self.assertEquals(returned_json_data[0]['expenses_player_salaries'], -150) def test_user_can_see_his_finances_diff_when_given_only_newer_matchday(self): - third_matchday = MatchdayFactory.create(number=self.matchday.number+2) - FinanceFactory.create(user=self.user1, matchday=third_matchday, balance=2500, income_visitors_league=250, expenses_player_salaries=250) + third_matchday = MatchdayFactory.create(number=self.matchday.number + 2) + FinanceFactory.create(user=self.user1, matchday=third_matchday, balance=2500, income_visitors_league=250, + expenses_player_salaries=250) response = self.client.get(reverse('core:ofm:finances_json'), {'newer_matchday_season': third_matchday.season.number, 'newer_matchday': third_matchday.number - }) + }) self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) diff --git a/core/tests/unit/views/test_ofm_player_detail_view.py b/core/tests/unit/views/test_ofm_player_detail_view.py index 6cf2303..5608742 100644 --- a/core/tests/unit/views/test_ofm_player_detail_view.py +++ b/core/tests/unit/views/test_ofm_player_detail_view.py @@ -1,9 +1,10 @@ import json -from core.factories.core_factories import MatchdayFactory, PlayerFactory, PlayerStatisticsFactory -from core.models import Contract, AwpBoundaries from django.core.urlresolvers import reverse from django.test import TestCase + +from core.factories.core_factories import MatchdayFactory, PlayerFactory, PlayerStatisticsFactory +from core.models import Contract, AwpBoundaries from users.models import OFMUser @@ -11,14 +12,17 @@ class OFMPlayerDetailViewTestCase(TestCase): def setUp(self): self.player = PlayerFactory.create() self.matchday = MatchdayFactory.create() - self.user1 = OFMUser.objects.create_user('alice', 'alice@ofmhelper.com', 'alice', ofm_username='alice', ofm_password='alice') - self.user2 = OFMUser.objects.create_user('bob', 'bob@ofmhelper.com', 'bob', ofm_username='bob', ofm_password='bob') - Contract.objects.create(user=self.user1, player=self.player, bought_on_matchday=self.matchday, sold_on_matchday=None) + self.user1 = OFMUser.objects.create_user('alice', 'alice@ofmhelper.com', 'alice', ofm_username='alice', + ofm_password='alice') + self.user2 = OFMUser.objects.create_user('bob', 'bob@ofmhelper.com', 'bob', ofm_username='bob', + ofm_password='bob') + Contract.objects.create(user=self.user1, player=self.player, bought_on_matchday=self.matchday, + sold_on_matchday=None) self.client.login(username='alice', password='alice') def test_user_can_see_his_players(self): PlayerStatisticsFactory.create(player=self.player) - response = self.client.get('/ofm/players/'+str(self.player.id)) + response = self.client.get('/ofm/players/' + str(self.player.id)) self.assertEqual(response.status_code, 200) self.assertTrue('player' in response.context_data) self.assertTrue('player_age' in response.context_data) @@ -27,12 +31,11 @@ def test_user_can_see_his_players(self): def test_user_cannot_see_other_users_players(self): self.client.login(username='bob', password='bob') - response = self.client.get('/ofm/players/'+str(self.player.id)) + response = self.client.get('/ofm/players/' + str(self.player.id)) self.assertEqual(response.status_code, 200) self.assertFalse('player' in response.context_data) def test_player_chart_json(self): - PlayerStatisticsFactory.create(player=self.player, matchday=self.matchday) awp_boundaries = AwpBoundaries.get_or_create_from_matchday(self.matchday) @@ -53,7 +56,6 @@ def test_player_chart_json(self): self.assertTrue('categories' in returned_json_data) def test_player_chart_shows_awp_boundaries_which_are_only_greater_than_my_strength(self): - PlayerStatisticsFactory.create(player=self.player, matchday=self.matchday, strength=3, awp=3500) awp_boundaries = AwpBoundaries.get_or_create_from_matchday(self.matchday) @@ -74,9 +76,9 @@ def test_player_chart_shows_awp_boundaries_which_are_only_greater_than_my_streng self.assertEquals([4000], returned_json_data['series'][1]['data']) def test_player_chart_shows_reached_but_not_promoted_awp_boundary(self): - PlayerStatisticsFactory.create(player=self.player, matchday=self.matchday, strength=2, awp=2800) - PlayerStatisticsFactory.create(player=self.player, matchday=MatchdayFactory.create(number=1), strength=2, awp=3500) + PlayerStatisticsFactory.create(player=self.player, matchday=MatchdayFactory.create(number=1), strength=2, + awp=3500) awp_boundaries = AwpBoundaries.get_or_create_from_matchday(self.matchday) awp_boundaries[2] = 2000 @@ -93,14 +95,13 @@ def test_player_chart_shows_reached_but_not_promoted_awp_boundary(self): self.assertEquals('AWP-Grenze: 3', returned_json_data['series'][1]['name']) self.assertTrue('data' in returned_json_data['series'][1]) - self.assertEquals([3000]*2, returned_json_data['series'][1]['data']) + self.assertEquals([3000] * 2, returned_json_data['series'][1]['data']) self.assertEquals('AWP-Grenze: 4', returned_json_data['series'][2]['name']) self.assertTrue('data' in returned_json_data['series'][2]) - self.assertEquals([4000]*2, returned_json_data['series'][2]['data']) + self.assertEquals([4000] * 2, returned_json_data['series'][2]['data']) def test_player_chart_does_not_show_boundary_if_promoted(self): - PlayerStatisticsFactory.create(player=self.player, matchday=self.matchday, strength=2, awp=2800) matchday_9 = MatchdayFactory.create(number=9) PlayerStatisticsFactory.create(player=self.player, matchday=matchday_9, strength=3, awp=3500) @@ -127,7 +128,6 @@ def test_player_chart_does_not_show_boundary_if_promoted(self): self.assertEquals([3800, 4000], returned_json_data['series'][1]['data']) def test_player_chart_shows_different_awp_boundaries(self): - matchday_9 = MatchdayFactory.create(number=9) PlayerStatisticsFactory.create(player=self.player, matchday=self.matchday) diff --git a/core/tests/unit/views/test_ofm_player_statistics_view.py b/core/tests/unit/views/test_ofm_player_statistics_view.py index 15d9a2d..d93dfe8 100644 --- a/core/tests/unit/views/test_ofm_player_statistics_view.py +++ b/core/tests/unit/views/test_ofm_player_statistics_view.py @@ -1,9 +1,10 @@ import json -from core.factories.core_factories import MatchdayFactory, PlayerFactory, PlayerStatisticsFactory -from core.models import Contract, AwpBoundaries from django.core.urlresolvers import reverse from django.test import TestCase + +from core.factories.core_factories import MatchdayFactory, PlayerFactory, PlayerStatisticsFactory +from core.models import Contract, AwpBoundaries from users.models import OFMUser @@ -12,11 +13,14 @@ def setUp(self): self.player = PlayerFactory.create() self.matchday = MatchdayFactory.create() self.second_matchday = MatchdayFactory.create(number=1) - self.user1 = OFMUser.objects.create_user(username='alice', email='alice@ofmhelper.com', password='alice', ofm_username='alice', ofm_password='alice') - Contract.objects.create(user=self.user1, player=self.player, bought_on_matchday=self.matchday, sold_on_matchday=None) + self.user1 = OFMUser.objects.create_user(username='alice', email='alice@ofmhelper.com', password='alice', + ofm_username='alice', ofm_password='alice') + Contract.objects.create(user=self.user1, player=self.player, bought_on_matchday=self.matchday, + sold_on_matchday=None) self.client.login(username='alice', password='alice') PlayerStatisticsFactory.create(player=self.player, matchday=self.matchday) - PlayerStatisticsFactory.create(player=self.player, matchday=self.second_matchday, ep=3, tp=6, awp=4, freshness=5) + PlayerStatisticsFactory.create(player=self.player, matchday=self.second_matchday, ep=3, tp=6, awp=4, + freshness=5) def test_user_can_see_table(self): response = self.client.get(reverse('core:ofm:player_statistics')) @@ -45,7 +49,7 @@ def test_user_can_see_his_latest_player_statistics_total_when_given_no_matchday( self.assertEquals(returned_json_data[0]['freshness'], 5) def test_user_can_see_his_player_statistics_diff_when_given_both_matchdays(self): - third_matchday = MatchdayFactory.create(number=self.matchday.number+2) + third_matchday = MatchdayFactory.create(number=self.matchday.number + 2) PlayerStatisticsFactory.create(player=self.player, matchday=third_matchday, ep=12, tp=15, awp=13, freshness=14) response = self.client.get(reverse('core:ofm:player_statistics_json'), @@ -65,13 +69,13 @@ def test_user_can_see_his_player_statistics_diff_when_given_both_matchdays(self) self.assertEquals(returned_json_data[0]['freshness'], 10) def test_user_can_see_his_player_statistics_diff_when_given_only_newer_matchday(self): - third_matchday = MatchdayFactory.create(number=self.matchday.number+2) + third_matchday = MatchdayFactory.create(number=self.matchday.number + 2) PlayerStatisticsFactory.create(player=self.player, matchday=third_matchday, ep=12, tp=15, awp=13, freshness=14) response = self.client.get(reverse('core:ofm:player_statistics_json'), {'newer_matchday_season': third_matchday.season.number, 'newer_matchday': third_matchday.number - }) + }) returned_json_data = json.loads(response.content.decode('utf-8')) self.assertEquals(returned_json_data[0]['position'], 'TW') @@ -83,7 +87,6 @@ def test_user_can_see_his_player_statistics_diff_when_given_only_newer_matchday( self.assertEquals(returned_json_data[0]['freshness'], 14) def test_user_can_see_players_diff_to_next_awp_boundary_given_no_matchday(self): - awp_boundaries = AwpBoundaries.get_or_create_from_matchday(self.matchday) awp_boundaries[2] = 20 @@ -93,7 +96,6 @@ def test_user_can_see_players_diff_to_next_awp_boundary_given_no_matchday(self): self.assertEquals(returned_json_data[0]['awp_to_next_bound'], 16) def test_user_can_see_players_diff_to_next_awp_boundary_given_matchdays(self): - awp_boundaries = AwpBoundaries.get_or_create_from_matchday(self.matchday) awp_boundaries[2] = 20 @@ -109,7 +111,8 @@ def test_user_can_see_players_diff_to_next_awp_boundary_given_matchdays(self): def test_player_leaves_team_shows_only_older_player_data(self): player2 = PlayerFactory.create(name="Tricia McMillan") - Contract.objects.create(user=self.user1, player=player2, bought_on_matchday=self.matchday, sold_on_matchday=self.matchday) + Contract.objects.create(user=self.user1, player=player2, bought_on_matchday=self.matchday, + sold_on_matchday=self.matchday) PlayerStatisticsFactory.create(player=player2, matchday=self.matchday, ep=3, tp=6, awp=4, freshness=5) response = self.client.get(reverse('core:ofm:player_statistics_json'), @@ -130,7 +133,8 @@ def test_player_leaves_team_shows_only_older_player_data(self): def test_player_joins_team_shows_only_older_player_data(self): player2 = PlayerFactory.create(name="Tricia McMillan") - Contract.objects.create(user=self.user1, player=player2, bought_on_matchday=self.matchday, sold_on_matchday=None) + Contract.objects.create(user=self.user1, player=player2, bought_on_matchday=self.matchday, + sold_on_matchday=None) PlayerStatisticsFactory.create(player=player2, matchday=self.second_matchday, ep=3, tp=6, awp=4, freshness=5) @@ -139,7 +143,7 @@ def test_player_joins_team_shows_only_older_player_data(self): 'newer_matchday': self.second_matchday.number, 'older_matchday_season': self.matchday.season.number, 'older_matchday': self.matchday.number - }) + }) returned_json_data = json.loads(response.content.decode('utf-8')) self.assertEquals(len(returned_json_data), 1) diff --git a/core/tests/unit/views/test_ofm_stadium_detail_view.py b/core/tests/unit/views/test_ofm_stadium_detail_view.py index a10ab4a..c5164bb 100644 --- a/core/tests/unit/views/test_ofm_stadium_detail_view.py +++ b/core/tests/unit/views/test_ofm_stadium_detail_view.py @@ -9,8 +9,10 @@ class OFMStadiumDetailsViewTestCase(TestCase): def setUp(self): self.matchday = MatchdayFactory.create() self.second_matchday = MatchdayFactory.create(number=1) - self.user1 = OFMUser.objects.create_user(username='alice', email='alice@ofmhelper.com', password='alice', ofm_username='alice', ofm_password='alice') - self.user2 = OFMUser.objects.create_user('bob', 'bob@ofmhelper.com', 'bob', ofm_username='bob', ofm_password='bob') + self.user1 = OFMUser.objects.create_user(username='alice', email='alice@ofmhelper.com', password='alice', + ofm_username='alice', ofm_password='alice') + self.user2 = OFMUser.objects.create_user('bob', 'bob@ofmhelper.com', 'bob', ofm_username='bob', + ofm_password='bob') self.match = MatchFactory.create(user=self.user1) self.stadium_stat = MatchStadiumStatisticsFactory.create(match=self.match) self.north_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='N') @@ -20,7 +22,7 @@ def setUp(self): self.client.login(username='alice', password='alice') def test_user_can_see_his_data(self): - response = self.client.get('/ofm/stadium/'+str(self.stadium_stat.id)) + response = self.client.get('/ofm/stadium/' + str(self.stadium_stat.id)) self.assertEqual(response.status_code, 200) self.assertTrue('stadium_stat' in response.context_data) self.assertTrue('north_stand' in response.context_data) @@ -30,12 +32,10 @@ def test_user_can_see_his_data(self): def test_user_cannot_see_other_users_data(self): self.client.login(username='bob', password='bob') - response = self.client.get('/ofm/stadium/'+str(self.stadium_stat.id)) + response = self.client.get('/ofm/stadium/' + str(self.stadium_stat.id)) self.assertEqual(response.status_code, 200) self.assertFalse('stadium_stat' in response.context_data) self.assertFalse('north_stand' in response.context_data) self.assertFalse('south_stand' in response.context_data) self.assertFalse('west_stand' in response.context_data) self.assertFalse('east_stand' in response.context_data) - - diff --git a/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py b/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py index 9194a94..cde8b05 100644 --- a/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py +++ b/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py @@ -11,8 +11,10 @@ class OFMStadiumStandStatisticsViewTestCase(TestCase): def setUp(self): self.matchday = MatchdayFactory.create() - self.user1 = OFMUser.objects.create_user(username='alice', email='alice@ofmhelper.com', password='alice', ofm_username='alice', ofm_password='alice') - self.user2 = OFMUser.objects.create_user('bob', 'bob@ofmhelper.com', 'bob', ofm_username='bob', ofm_password='bob') + self.user1 = OFMUser.objects.create_user(username='alice', email='alice@ofmhelper.com', password='alice', + ofm_username='alice', ofm_password='alice') + self.user2 = OFMUser.objects.create_user('bob', 'bob@ofmhelper.com', 'bob', ofm_username='bob', + ofm_password='bob') self.match = MatchFactory.create(user=self.user1) self.stadium_stat = MatchStadiumStatisticsFactory.create(match=self.match) self.north_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='N') @@ -49,5 +51,3 @@ def test_finance_balance_chart_json(self): self.assertTrue('data' in returned_json_data['series'][0]) self.assertTrue('categories' in returned_json_data) self.assertTrue('yAxis' in returned_json_data) - - diff --git a/core/tests/unit/views/test_parser_view.py b/core/tests/unit/views/test_parser_view.py index d13a7b5..5e667a2 100644 --- a/core/tests/unit/views/test_parser_view.py +++ b/core/tests/unit/views/test_parser_view.py @@ -14,7 +14,7 @@ class ParserViewTest(TestCase): def setUp(self): MatchdayFactory.create(season__number=100, number=1) - + self.user = OFMUser.objects.create_user('name', '', 'pass', ofm_username='name', ofm_password='pass') self.client.login(username='name', password='pass') @@ -42,7 +42,8 @@ def test_player_parser_view(self, matchday_parser_mock, site_manager_mock, playe @patch('core.managers.parser_manager.MatchdayParser') @patch('core.managers.parser_manager.PlayersParser') @patch('core.managers.parser_manager.PlayerStatisticsParser') - def test_player_statistics_parser_view(self, matchday_parser_mock, player_parser_mock, site_manager_mock, player_statistics_parser_mock): + def test_player_statistics_parser_view(self, matchday_parser_mock, player_parser_mock, site_manager_mock, + player_statistics_parser_mock): response = self.client.get(reverse('core:trigger_player_statistics_parsing')) self.assertEqual(response.status_code, 302) @@ -99,4 +100,3 @@ def test_parser_view(self, site_manager_mock, parse_matchday_mock, parse_players assert parse_all_matches_mock.called assert parse_awp_mock.called assert parse_version_mock.called - diff --git a/ofm_helper/settings/docker.py b/ofm_helper/settings/docker.py index fc6e338..4d04f14 100644 --- a/ofm_helper/settings/docker.py +++ b/ofm_helper/settings/docker.py @@ -6,14 +6,14 @@ # DB DATABASES = { - 'default': { - 'ENGINE': 'django.db.backends.postgresql', - 'NAME': 'postgres', - 'USER': 'postgres', - 'HOST': 'db', - 'PORT': 5432, - } - } + 'default': { + 'ENGINE': 'django.db.backends.postgresql', + 'NAME': 'postgres', + 'USER': 'postgres', + 'HOST': 'db', + 'PORT': 5432, + } +} # CACHING CACHE_HOST = 'redis' diff --git a/pytest.ini b/pytest.ini index 86cc7e2..4ef58b6 100644 --- a/pytest.ini +++ b/pytest.ini @@ -1,5 +1,5 @@ [pytest] DJANGO_SETTINGS_MODULE=ofm_helper.settings.dev -pep8ignore = E501 +pep8ignore = E501 E125 E126 E127 flakes-ignore = settings/*.py ImportStarUsage ImportStarUsed diff --git a/users/tests/unit/test_user_models.py b/users/tests/unit/test_user_models.py index d684a6a..81061fd 100644 --- a/users/tests/unit/test_user_models.py +++ b/users/tests/unit/test_user_models.py @@ -9,5 +9,3 @@ def test_create_season(self): self.assertIsNotNone(u) self.assertEqual(u.username, 'test') self.assertEqual(u.password, '1234') - - From 443f6e58a3e0b3f55949f4fef9f563f0c792b728 Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Mon, 5 Dec 2016 16:46:50 +0100 Subject: [PATCH 07/71] auto run python linter, WIP --- .pylintrc | 410 ++++++++++++++++++++++++++++++++++++++++++++++++++++ .travis.yml | 3 +- 2 files changed, 412 insertions(+), 1 deletion(-) create mode 100644 .pylintrc diff --git a/.pylintrc b/.pylintrc new file mode 100644 index 0000000..9baba07 --- /dev/null +++ b/.pylintrc @@ -0,0 +1,410 @@ +[MASTER] + +# Specify a configuration file. +#rcfile= + +# Python code to execute, usually for sys.path manipulation such as +# pygtk.require(). +#init-hook= + +# Add files or directories to the blacklist. They should be base names, not +# paths. +ignore=CSV + +# Add files or directories matching the regex patterns to the blacklist. The +# regex matches against base names, not paths. +ignore-patterns= + +# Pickle collected data for later comparisons. +persistent=yes + +# List of plugins (as comma separated values of python modules names) to load, +# usually to register additional checkers. +load-plugins= + +# Use multiple processes to speed up Pylint. +jobs=4 + +# Allow loading of arbitrary C extensions. Extensions are imported into the +# active Python interpreter and may run arbitrary code. +unsafe-load-any-extension=no + +# A comma-separated list of package or module names from where C extensions may +# be loaded. Extensions are loading into the active Python interpreter and may +# run arbitrary code +extension-pkg-whitelist= + +# Allow optimization of some AST trees. This will activate a peephole AST +# optimizer, which will apply various small optimizations. For instance, it can +# be used to obtain the result of joining multiple strings with the addition +# operator. Joining a lot of strings can lead to a maximum recursion error in +# Pylint and this flag can prevent that. It has one side effect, the resulting +# AST will be different than the one from reality. This option is deprecated +# and it will be removed in Pylint 2.0. +optimize-ast=no + + +[MESSAGES CONTROL] + +# Only show warnings with the listed confidence levels. Leave empty to show +# all. Valid levels: HIGH, INFERENCE, INFERENCE_FAILURE, UNDEFINED +confidence= + +# Enable the message, report, category or checker with the given id(s). You can +# either give multiple identifier separated by comma (,) or put this option +# multiple time (only on the command line, not in the configuration file where +# it should appear only once). See also the "--disable" option for examples. +#enable= +#enable=similarities,classes +enable=all + +# Disable the message, report, category or checker with the given id(s). You +# can either give multiple identifiers separated by comma (,) or put this +# option multiple times (only on the command line, not in the configuration +# file where it should appear only once).You can also use "--disable=all" to +# disable everything first and then reenable specific checks. For example, if +# you want to run only the similarities checker, you can use "--disable=all +# --enable=similarities". If you want to run only the classes checker, but have +# no Warning level messages displayed, use"--disable=all --enable=classes +# --disable=W" +#disable=all +#disable=map-builtin-not-iterating,reduce-builtin,parameter-unpacking,buffer-builtin,raw_input-builtin,execfile-builtin,raising-string,cmp-method,old-octal-literal,suppressed-message,print-statement,import-star-module-level,indexing-exception,long-builtin,apply-builtin,dict-view-method,old-division,unicode-builtin,setslice-method,unichr-builtin,round-builtin,oct-method,next-method-called,unpacking-in-except,metaclass-assignment,using-cmp-argument,old-raise-syntax,cmp-builtin,file-builtin,old-ne-operator,basestring-builtin,xrange-builtin,useless-suppression,nonzero-method,standarderror-builtin,range-builtin-not-iterating,delslice-method,no-absolute-import,coerce-method,input-builtin,backtick,long-suffix,intern-builtin,coerce-builtin,zip-builtin-not-iterating,filter-builtin-not-iterating,reload-builtin,getslice-method,hex-method,dict-iter-method +disable=missing-docstring,unused-import,wildcard-import,unused-wildcard-import,no-method + +[REPORTS] + +# Set the output format. Available formats are text, parseable, colorized, msvs +# (visual studio) and html. You can also give a reporter class, eg +# mypackage.mymodule.MyReporterClass. +output-format=text + +# Put messages in a separate file for each module / package specified on the +# command line instead of printing them on stdout. Reports (if any) will be +# written in a file name "pylint_global.[txt|html]". This option is deprecated +# and it will be removed in Pylint 2.0. +files-output=no + +# Tells whether to display a full report or only the messages +reports=yes + +# Python expression which should return a note less than 10 (10 is the highest +# note). You have access to the variables errors warning, statement which +# respectively contain the number of errors / warnings messages and the total +# number of statements analyzed. This is used by the global evaluation report +# (RP0004). +evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10) + +# Template used to display messages. This is a python new-style format string +# used to format the message information. See doc for all details +#msg-template= + + +[SPELLING] + +# Spelling dictionary name. Available dictionaries: none. To make it working +# install python-enchant package. +spelling-dict= + +# List of comma separated words that should not be checked. +spelling-ignore-words= + +# A path to a file that contains private dictionary; one word per line. +spelling-private-dict-file= + +# Tells whether to store unknown words to indicated private dictionary in +# --spelling-private-dict-file option instead of raising a message. +spelling-store-unknown-words=no + + +[SIMILARITIES] + +# Minimum lines number of a similarity. +min-similarity-lines=4 + +# Ignore comments when computing similarities. +ignore-comments=yes + +# Ignore docstrings when computing similarities. +ignore-docstrings=yes + +# Ignore imports when computing similarities. +ignore-imports=no + + +[VARIABLES] + +# Tells whether we should check for unused import in __init__ files. +init-import=no + +# A regular expression matching the name of dummy variables (i.e. expectedly +# not used). +dummy-variables-rgx=(_+[a-zA-Z0-9]*?$)|dummy + +# List of additional names supposed to be defined in builtins. Remember that +# you should avoid to define new builtins when possible. +additional-builtins= + +# List of strings which can identify a callback function by name. A callback +# name must start or end with one of those strings. +callbacks=cb_,_cb + +# List of qualified module names which can have objects that can redefine +# builtins. +redefining-builtins-modules=six.moves,future.builtins + + +[TYPECHECK] + +# Tells whether missing members accessed in mixin class should be ignored. A +# mixin class is detected if its name ends with "mixin" (case insensitive). +ignore-mixin-members=yes + +# List of module names for which member attributes should not be checked +# (useful for modules/projects where namespaces are manipulated during runtime +# and thus existing member attributes cannot be deduced by static analysis. It +# supports qualified module names, as well as Unix pattern matching. +ignored-modules= + +# List of class names for which member attributes should not be checked (useful +# for classes with dynamically set attributes). This supports the use of +# qualified names. +ignored-classes=optparse.Values,thread._local,_thread._local + +# List of members which are set dynamically and missed by pylint inference +# system, and so shouldn't trigger E1101 when accessed. Python regular +# expressions are accepted. +generated-members= + +# List of decorators that produce context managers, such as +# contextlib.contextmanager. Add to this list to register other decorators that +# produce valid context managers. +contextmanager-decorators=contextlib.contextmanager + + +[MISCELLANEOUS] + +# List of note tags to take in consideration, separated by a comma. +notes=FIXME,XXX,TODO + + +[LOGGING] + +# Logging modules to check that the string format arguments are in logging +# function parameter format +logging-modules=logging + + +[FORMAT] + +# Maximum number of characters on a single line. +max-line-length=120 + +# Regexp for a line that is allowed to be longer than the limit. +ignore-long-lines=^\s*(# )??$ + +# Allow the body of an if to be on the same line as the test if there is no +# else. +single-line-if-stmt=no + +# List of optional constructs for which whitespace checking is disabled. `dict- +# separator` is used to allow tabulation in dicts, etc.: {1 : 1,\n222: 2}. +# `trailing-comma` allows a space between comma and closing bracket: (a, ). +# `empty-line` allows space-only lines. +no-space-check=trailing-comma,dict-separator + +# Maximum number of lines in a module +max-module-lines=1000 + +# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1 +# tab). +indent-string=' ' + +# Number of spaces of indent required inside a hanging or continued line. +indent-after-paren=4 + +# Expected format of line ending, e.g. empty (any line ending), LF or CRLF. +expected-line-ending-format= + + +[BASIC] + +# Good variable names which should always be accepted, separated by a comma +good-names=i,j,k,ex,Run,_ + +# Bad variable names which should always be refused, separated by a comma +bad-names=foo,bar,baz,toto,tutu,tata + +# Colon-delimited sets of names that determine each other's naming style when +# the name regexes allow several styles. +name-group= + +# Include a hint for the correct naming format with invalid-name +include-naming-hint=no + +# List of decorators that produce properties, such as abc.abstractproperty. Add +# to this list to register other decorators that produce valid properties. +property-classes=abc.abstractproperty + +# Regular expression matching correct inline iteration names +inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$ + +# Naming hint for inline iteration names +inlinevar-name-hint=[A-Za-z_][A-Za-z0-9_]*$ + +# Regular expression matching correct attribute names +attr-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Naming hint for attribute names +attr-name-hint=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression matching correct function names +function-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Naming hint for function names +function-name-hint=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression matching correct variable names +variable-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Naming hint for variable names +variable-name-hint=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression matching correct module names +module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ + +# Naming hint for module names +module-name-hint=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$ + +# Regular expression matching correct argument names +argument-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Naming hint for argument names +argument-name-hint=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression matching correct method names +method-rgx=[a-z_][a-z0-9_]{2,30}$ + +# Naming hint for method names +method-name-hint=[a-z_][a-z0-9_]{2,30}$ + +# Regular expression matching correct class names +class-rgx=[A-Z_][a-zA-Z0-9]+$ + +# Naming hint for class names +class-name-hint=[A-Z_][a-zA-Z0-9]+$ + +# Regular expression matching correct class attribute names +class-attribute-rgx=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ + +# Naming hint for class attribute names +class-attribute-name-hint=([A-Za-z_][A-Za-z0-9_]{2,30}|(__.*__))$ + +# Regular expression matching correct constant names +const-rgx=(([A-Z_][A-Z0-9_]*)|(__.*__))$ + +# Naming hint for constant names +const-name-hint=(([A-Z_][A-Z0-9_]*)|(__.*__))$ + +# Regular expression which should only match function or class names that do +# not require a docstring. +no-docstring-rgx=^_ + +# Minimum line length for functions/classes that require docstrings, shorter +# ones are exempt. +docstring-min-length=-1 + + +[ELIF] + +# Maximum number of nested blocks for function / method body +max-nested-blocks=5 + + +[DESIGN] + +# Maximum number of arguments for function / method +max-args=5 + +# Argument names that match this expression will be ignored. Default to name +# with leading underscore +ignored-argument-names=_.* + +# Maximum number of locals for function / method body +max-locals=15 + +# Maximum number of return / yield for function / method body +max-returns=6 + +# Maximum number of branch for function / method body +max-branches=12 + +# Maximum number of statements in function / method body +max-statements=50 + +# Maximum number of parents for a class (see R0901). +max-parents=7 + +# Maximum number of attributes for a class (see R0902). +max-attributes=7 + +# Minimum number of public methods for a class (see R0903). +min-public-methods=2 + +# Maximum number of public methods for a class (see R0904). +max-public-methods=20 + +# Maximum number of boolean expressions in a if statement +max-bool-expr=5 + + +[CLASSES] + +# List of method names used to declare (i.e. assign) instance attributes. +defining-attr-methods=__init__,__new__,setUp + +# List of valid names for the first argument in a class method. +valid-classmethod-first-arg=cls + +# List of valid names for the first argument in a metaclass class method. +valid-metaclass-classmethod-first-arg=mcs + +# List of member names, which should be excluded from the protected access +# warning. +exclude-protected=_asdict,_fields,_replace,_source,_make + + +[IMPORTS] + +# Deprecated modules which should not be used, separated by a comma +deprecated-modules=optparse + +# Create a graph of every (i.e. internal and external) dependencies in the +# given file (report RP0402 must not be disabled) +import-graph= + +# Create a graph of external dependencies in the given file (report RP0402 must +# not be disabled) +ext-import-graph= + +# Create a graph of internal dependencies in the given file (report RP0402 must +# not be disabled) +int-import-graph= + +# Force import order to recognize a module as part of the standard +# compatibility libraries. +known-standard-library= + +# Force import order to recognize a module as part of a third party library. +known-third-party=enchant + +# Analyse import fallback blocks. This can be used to support both Python 2 and +# 3 compatible code, which means that the block might have code that exists +# only in one or another interpreter, leading to false positives when analysed. +analyse-fallback-blocks=no + + +[EXCEPTIONS] + +# Exceptions that will emit a warning when being caught. Defaults to +# "Exception" +overgeneral-exceptions=Exception diff --git a/.travis.yml b/.travis.yml index 90c1afa..c3810a8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -12,9 +12,10 @@ install: script: - "./manage.py migrate" - coverage run --branch --source . manage.py test -- py.test --mccabe -m mccabe - py.test --flakes - py.test --pep8 +- py.test --mccabe -m mccabe +- py.test --pylint -m pylint --ignore=core/migrations --ignore=users/migrations --ignore=manage.py notifications: email: recipients: From 17ea19cf45a4ed29f52886185c955424b7ede27f Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Mon, 5 Dec 2016 17:00:17 +0100 Subject: [PATCH 08/71] add pylint to deps + ignore more errors --- .pylintrc | 2 +- travis_requirements.txt | 1 + 2 files changed, 2 insertions(+), 1 deletion(-) diff --git a/.pylintrc b/.pylintrc index 9baba07..f0dda5e 100644 --- a/.pylintrc +++ b/.pylintrc @@ -69,7 +69,7 @@ enable=all # --disable=W" #disable=all #disable=map-builtin-not-iterating,reduce-builtin,parameter-unpacking,buffer-builtin,raw_input-builtin,execfile-builtin,raising-string,cmp-method,old-octal-literal,suppressed-message,print-statement,import-star-module-level,indexing-exception,long-builtin,apply-builtin,dict-view-method,old-division,unicode-builtin,setslice-method,unichr-builtin,round-builtin,oct-method,next-method-called,unpacking-in-except,metaclass-assignment,using-cmp-argument,old-raise-syntax,cmp-builtin,file-builtin,old-ne-operator,basestring-builtin,xrange-builtin,useless-suppression,nonzero-method,standarderror-builtin,range-builtin-not-iterating,delslice-method,no-absolute-import,coerce-method,input-builtin,backtick,long-suffix,intern-builtin,coerce-builtin,zip-builtin-not-iterating,filter-builtin-not-iterating,reload-builtin,getslice-method,hex-method,dict-iter-method -disable=missing-docstring,unused-import,wildcard-import,unused-wildcard-import,no-method +disable=missing-docstring,unused-import,wildcard-import,unused-wildcard-import,no-method,too-few-public-methods,invalid-name,no-member,bad-continuation [REPORTS] diff --git a/travis_requirements.txt b/travis_requirements.txt index 100a10d..f3a7b14 100644 --- a/travis_requirements.txt +++ b/travis_requirements.txt @@ -4,3 +4,4 @@ pytest-django pytest-mccabe pytest-flakes pytest-pep8 +pytest-pylint From 21d97c09b059375ac7206ad3dcda2ba5fa97d315 Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Mon, 5 Dec 2016 17:24:08 +0100 Subject: [PATCH 09/71] assertEquals is deprecated --- .../unit/parser/test_awp_boundaries_parser.py | 60 +++++++------- .../parser/test_future_match_row_parser.py | 56 ++++++------- core/tests/unit/parser/test_match_parser.py | 56 ++++++------- .../parser/test_player_statistics_parser.py | 50 ++++++------ core/tests/unit/parser/test_players_parser.py | 22 ++--- .../test_stadium_stand_statistics_parser.py | 64 +++++++-------- ...um_stand_statistics_parser_construction.py | 36 ++++----- .../parser/test_stadium_statistics_parser.py | 44 +++++----- .../test_won_by_default_match_row_parser.py | 56 ++++++------- core/tests/unit/test_core_models.py | 48 +++++------ .../views/test_ofm_finances_charts_views.py | 6 +- .../unit/views/test_ofm_finances_view.py | 40 +++++----- .../tests/unit/views/test_ofm_matches_view.py | 8 +- .../unit/views/test_ofm_player_detail_view.py | 34 ++++---- .../views/test_ofm_player_statistics_view.py | 80 +++++++++---------- .../test_ofm_stadium_stand_statistics_view.py | 10 +-- .../views/test_ofm_stadium_statistics_view.py | 44 +++++----- core/tests/unit/views/test_parser_view.py | 2 +- core/tests/unit/views/test_settings_view.py | 4 +- 19 files changed, 361 insertions(+), 359 deletions(-) diff --git a/core/tests/unit/parser/test_awp_boundaries_parser.py b/core/tests/unit/parser/test_awp_boundaries_parser.py index 2850719..7a14017 100644 --- a/core/tests/unit/parser/test_awp_boundaries_parser.py +++ b/core/tests/unit/parser/test_awp_boundaries_parser.py @@ -19,35 +19,35 @@ def setUp(self): self.awp_boundaries = self.parser.parse() def test_parser(self): - self.assertEquals(type(self.awp_boundaries), AwpBoundaries) - self.assertEquals(AwpBoundaries.objects.count(), 1) + self.assertEqual(type(self.awp_boundaries), AwpBoundaries) + self.assertEqual(AwpBoundaries.objects.count(), 1) - self.assertEquals(self.awp_boundaries[2], 113) - self.assertEquals(self.awp_boundaries[3], 332) - self.assertEquals(self.awp_boundaries[4], 569) - self.assertEquals(self.awp_boundaries[5], 883) - self.assertEquals(self.awp_boundaries[6], 1306) - self.assertEquals(self.awp_boundaries[7], 1865) - self.assertEquals(self.awp_boundaries[8], 2641) - self.assertEquals(self.awp_boundaries[9], 3616) - self.assertEquals(self.awp_boundaries[10], 4649) - self.assertEquals(self.awp_boundaries[11], 5673) - self.assertEquals(self.awp_boundaries[12], 6694) - self.assertEquals(self.awp_boundaries[13], 7766) - self.assertEquals(self.awp_boundaries[14], 8893) - self.assertEquals(self.awp_boundaries[15], 10049) - self.assertEquals(self.awp_boundaries[16], 11141) - self.assertEquals(self.awp_boundaries[17], 12203) - self.assertEquals(self.awp_boundaries[18], 13240) - self.assertEquals(self.awp_boundaries[19], 14230) - self.assertEquals(self.awp_boundaries[20], 15254) - self.assertEquals(self.awp_boundaries[21], 16309) - self.assertEquals(self.awp_boundaries[22], 17311) - self.assertEquals(self.awp_boundaries[23], 18302) - self.assertEquals(self.awp_boundaries[24], 18999) - self.assertEquals(self.awp_boundaries[25], 20078) - self.assertEquals(self.awp_boundaries[26], 20795) - self.assertEquals(self.awp_boundaries[27], 21105) + self.assertEqual(self.awp_boundaries[2], 113) + self.assertEqual(self.awp_boundaries[3], 332) + self.assertEqual(self.awp_boundaries[4], 569) + self.assertEqual(self.awp_boundaries[5], 883) + self.assertEqual(self.awp_boundaries[6], 1306) + self.assertEqual(self.awp_boundaries[7], 1865) + self.assertEqual(self.awp_boundaries[8], 2641) + self.assertEqual(self.awp_boundaries[9], 3616) + self.assertEqual(self.awp_boundaries[10], 4649) + self.assertEqual(self.awp_boundaries[11], 5673) + self.assertEqual(self.awp_boundaries[12], 6694) + self.assertEqual(self.awp_boundaries[13], 7766) + self.assertEqual(self.awp_boundaries[14], 8893) + self.assertEqual(self.awp_boundaries[15], 10049) + self.assertEqual(self.awp_boundaries[16], 11141) + self.assertEqual(self.awp_boundaries[17], 12203) + self.assertEqual(self.awp_boundaries[18], 13240) + self.assertEqual(self.awp_boundaries[19], 14230) + self.assertEqual(self.awp_boundaries[20], 15254) + self.assertEqual(self.awp_boundaries[21], 16309) + self.assertEqual(self.awp_boundaries[22], 17311) + self.assertEqual(self.awp_boundaries[23], 18302) + self.assertEqual(self.awp_boundaries[24], 18999) + self.assertEqual(self.awp_boundaries[25], 20078) + self.assertEqual(self.awp_boundaries[26], 20795) + self.assertEqual(self.awp_boundaries[27], 21105) def test_parser_does_not_create_new_boundaries_object_if_already_exists_for_quarter(self): self.matchday = MatchdayFactory.create(number=2) @@ -55,7 +55,7 @@ def test_parser_does_not_create_new_boundaries_object_if_already_exists_for_quar self.user, self.matchday) self.parser.parse() - self.assertEquals(AwpBoundaries.objects.count(), 1) + self.assertEqual(AwpBoundaries.objects.count(), 1) def test_parser_creates_new_boundaries_object(self): self.matchday = MatchdayFactory.create(number=17) @@ -63,4 +63,4 @@ def test_parser_creates_new_boundaries_object(self): self.user, self.matchday) self.parser.parse() - self.assertEquals(AwpBoundaries.objects.count(), 2) + self.assertEqual(AwpBoundaries.objects.count(), 2) diff --git a/core/tests/unit/parser/test_future_match_row_parser.py b/core/tests/unit/parser/test_future_match_row_parser.py index a24b814..bafa714 100644 --- a/core/tests/unit/parser/test_future_match_row_parser.py +++ b/core/tests/unit/parser/test_future_match_row_parser.py @@ -23,32 +23,32 @@ def setUp(self): self.match_stat = parser.parse() def test_match_parser_general_informations(self): - self.assertEquals(type(self.match_stat), Match) - self.assertEquals(self.match_stat.matchday.number, '34') - self.assertEquals(self.match_stat.user, self.user) - self.assertEquals(self.match_stat.match_type, 'L') - self.assertEquals(self.match_stat.venue, '') - self.assertEquals(self.match_stat.is_in_future, True) + self.assertEqual(type(self.match_stat), Match) + self.assertEqual(self.match_stat.matchday.number, '34') + self.assertEqual(self.match_stat.user, self.user) + self.assertEqual(self.match_stat.match_type, 'L') + self.assertEqual(self.match_stat.venue, '') + self.assertEqual(self.match_stat.is_in_future, True) def test_match_home_team_statistics(self): - self.assertEquals(type(self.match_stat.home_team_statistics), MatchTeamStatistics) - self.assertEquals(self.match_stat.home_team_statistics.score, 0) - self.assertEquals(self.match_stat.home_team_statistics.team_name, 'BSC Wittenau') - self.assertEquals(self.match_stat.home_team_statistics.strength, '60') - self.assertEquals(self.match_stat.home_team_statistics.ball_possession, 0) - self.assertEquals(self.match_stat.home_team_statistics.chances, 0) - self.assertEquals(self.match_stat.home_team_statistics.yellow_cards, 0) - self.assertEquals(self.match_stat.home_team_statistics.red_cards, 0) + self.assertEqual(type(self.match_stat.home_team_statistics), MatchTeamStatistics) + self.assertEqual(self.match_stat.home_team_statistics.score, 0) + self.assertEqual(self.match_stat.home_team_statistics.team_name, 'BSC Wittenau') + self.assertEqual(self.match_stat.home_team_statistics.strength, '60') + self.assertEqual(self.match_stat.home_team_statistics.ball_possession, 0) + self.assertEqual(self.match_stat.home_team_statistics.chances, 0) + self.assertEqual(self.match_stat.home_team_statistics.yellow_cards, 0) + self.assertEqual(self.match_stat.home_team_statistics.red_cards, 0) def test_match_guest_team_statistics(self): - self.assertEquals(type(self.match_stat.guest_team_statistics), MatchTeamStatistics) - self.assertEquals(self.match_stat.guest_team_statistics.score, 0) - self.assertEquals(self.match_stat.guest_team_statistics.team_name, 'Supporters Kiel') - self.assertEquals(self.match_stat.guest_team_statistics.strength, '28') - self.assertEquals(self.match_stat.guest_team_statistics.ball_possession, 0) - self.assertEquals(self.match_stat.guest_team_statistics.chances, 0) - self.assertEquals(self.match_stat.guest_team_statistics.yellow_cards, 0) - self.assertEquals(self.match_stat.guest_team_statistics.red_cards, 0) + self.assertEqual(type(self.match_stat.guest_team_statistics), MatchTeamStatistics) + self.assertEqual(self.match_stat.guest_team_statistics.score, 0) + self.assertEqual(self.match_stat.guest_team_statistics.team_name, 'Supporters Kiel') + self.assertEqual(self.match_stat.guest_team_statistics.strength, '28') + self.assertEqual(self.match_stat.guest_team_statistics.ball_possession, 0) + self.assertEqual(self.match_stat.guest_team_statistics.chances, 0) + self.assertEqual(self.match_stat.guest_team_statistics.yellow_cards, 0) + self.assertEqual(self.match_stat.guest_team_statistics.red_cards, 0) def test_match_gets_updated_on_parsing_again(self): testdata = open(os.path.join(TESTDATA_PATH, 'future_match_row_2.html'), encoding='utf8') @@ -58,9 +58,9 @@ def test_match_gets_updated_on_parsing_again(self): parser = FutureMatchRowParser(soup, self.user) match_stat2 = parser.parse() - self.assertEquals(self.match_stat.id, match_stat2.id) - self.assertEquals(self.match_stat.home_team_statistics.id, match_stat2.home_team_statistics.id) - self.assertEquals(self.match_stat.guest_team_statistics.id, match_stat2.guest_team_statistics.id) - self.assertEquals(match_stat2.home_team_statistics.strength, '61') - self.assertEquals(match_stat2.guest_team_statistics.strength, '29') - self.assertEquals(2, MatchTeamStatistics.objects.all().count()) + self.assertEqual(self.match_stat.id, match_stat2.id) + self.assertEqual(self.match_stat.home_team_statistics.id, match_stat2.home_team_statistics.id) + self.assertEqual(self.match_stat.guest_team_statistics.id, match_stat2.guest_team_statistics.id) + self.assertEqual(match_stat2.home_team_statistics.strength, '61') + self.assertEqual(match_stat2.guest_team_statistics.strength, '29') + self.assertEqual(2, MatchTeamStatistics.objects.all().count()) diff --git a/core/tests/unit/parser/test_match_parser.py b/core/tests/unit/parser/test_match_parser.py index 41bbb0f..ed910a1 100644 --- a/core/tests/unit/parser/test_match_parser.py +++ b/core/tests/unit/parser/test_match_parser.py @@ -20,32 +20,32 @@ def setUp(self): self.match_stat = parser.parse() def test_match_parser_general_informations(self): - self.assertEquals(type(self.match_stat), Match) - self.assertEquals(self.match_stat.matchday.number, '8') - self.assertEquals(self.match_stat.user, self.user) - self.assertEquals(self.match_stat.match_type, 'L') - self.assertEquals(self.match_stat.venue, 'Club-Mate-Arena') - self.assertEquals(self.match_stat.is_in_future, False) + self.assertEqual(type(self.match_stat), Match) + self.assertEqual(self.match_stat.matchday.number, '8') + self.assertEqual(self.match_stat.user, self.user) + self.assertEqual(self.match_stat.match_type, 'L') + self.assertEqual(self.match_stat.venue, 'Club-Mate-Arena') + self.assertEqual(self.match_stat.is_in_future, False) def test_match_home_team_statistics(self): - self.assertEquals(type(self.match_stat.home_team_statistics), MatchTeamStatistics) - self.assertEquals(self.match_stat.home_team_statistics.score, '0') - self.assertEquals(self.match_stat.home_team_statistics.team_name, 'BSC Wittenau') - self.assertEquals(self.match_stat.home_team_statistics.strength, '40') - self.assertEquals(self.match_stat.home_team_statistics.ball_possession, '37.4') - self.assertEquals(self.match_stat.home_team_statistics.chances, '0') - self.assertEquals(self.match_stat.home_team_statistics.yellow_cards, '0') - self.assertEquals(self.match_stat.home_team_statistics.red_cards, '0') + self.assertEqual(type(self.match_stat.home_team_statistics), MatchTeamStatistics) + self.assertEqual(self.match_stat.home_team_statistics.score, '0') + self.assertEqual(self.match_stat.home_team_statistics.team_name, 'BSC Wittenau') + self.assertEqual(self.match_stat.home_team_statistics.strength, '40') + self.assertEqual(self.match_stat.home_team_statistics.ball_possession, '37.4') + self.assertEqual(self.match_stat.home_team_statistics.chances, '0') + self.assertEqual(self.match_stat.home_team_statistics.yellow_cards, '0') + self.assertEqual(self.match_stat.home_team_statistics.red_cards, '0') def test_match_guest_team_statistics(self): - self.assertEquals(type(self.match_stat.guest_team_statistics), MatchTeamStatistics) - self.assertEquals(self.match_stat.guest_team_statistics.score, '3') - self.assertEquals(self.match_stat.guest_team_statistics.team_name, 'Ruhrorter SC') - self.assertEquals(self.match_stat.guest_team_statistics.strength, '67') - self.assertEquals(self.match_stat.guest_team_statistics.ball_possession, '62.6') - self.assertEquals(self.match_stat.guest_team_statistics.chances, '4') - self.assertEquals(self.match_stat.guest_team_statistics.yellow_cards, '0') - self.assertEquals(self.match_stat.guest_team_statistics.red_cards, '0') + self.assertEqual(type(self.match_stat.guest_team_statistics), MatchTeamStatistics) + self.assertEqual(self.match_stat.guest_team_statistics.score, '3') + self.assertEqual(self.match_stat.guest_team_statistics.team_name, 'Ruhrorter SC') + self.assertEqual(self.match_stat.guest_team_statistics.strength, '67') + self.assertEqual(self.match_stat.guest_team_statistics.ball_possession, '62.6') + self.assertEqual(self.match_stat.guest_team_statistics.chances, '4') + self.assertEqual(self.match_stat.guest_team_statistics.yellow_cards, '0') + self.assertEqual(self.match_stat.guest_team_statistics.red_cards, '0') def test_match_gets_updated_on_parsing_again(self): testdata = open(os.path.join(TESTDATA_PATH, 'home_match_2.html'), encoding='utf8') @@ -53,9 +53,9 @@ def test_match_gets_updated_on_parsing_again(self): parser = MatchParser(testdata, self.user, True) match_stat2 = parser.parse() - self.assertEquals(self.match_stat.id, match_stat2.id) - self.assertEquals(self.match_stat.home_team_statistics.id, match_stat2.home_team_statistics.id) - self.assertEquals(self.match_stat.guest_team_statistics.id, match_stat2.guest_team_statistics.id) - self.assertEquals(match_stat2.home_team_statistics.strength, '42') - self.assertEquals(match_stat2.guest_team_statistics.strength, '69') - self.assertEquals(2, MatchTeamStatistics.objects.all().count()) + self.assertEqual(self.match_stat.id, match_stat2.id) + self.assertEqual(self.match_stat.home_team_statistics.id, match_stat2.home_team_statistics.id) + self.assertEqual(self.match_stat.guest_team_statistics.id, match_stat2.guest_team_statistics.id) + self.assertEqual(match_stat2.home_team_statistics.strength, '42') + self.assertEqual(match_stat2.guest_team_statistics.strength, '69') + self.assertEqual(2, MatchTeamStatistics.objects.all().count()) diff --git a/core/tests/unit/parser/test_player_statistics_parser.py b/core/tests/unit/parser/test_player_statistics_parser.py index 42ca6ac..1480c6f 100644 --- a/core/tests/unit/parser/test_player_statistics_parser.py +++ b/core/tests/unit/parser/test_player_statistics_parser.py @@ -20,6 +20,8 @@ def setUp(self): country_no_greece = list(country_choices.keys())[list(country_choices.values()).index('Griechenland')] nationality_greece, success = Country.objects.get_or_create(country=country_no_greece) + self.assertTrue(success) + self.player = Player.objects.create(id='159883060', position='TW', name='Chrístos Tsigas', birth_season=season, nationality=nationality_greece) self.player = Player.objects.create(id='160195494', position='LV', name='Irwin O\'Canny', birth_season=season, nationality=nationality_greece) self.player = Player.objects.create(id='159341445', position='LMD', name='Jan Stemmler', birth_season=season, nationality=nationality_greece) @@ -30,49 +32,49 @@ def setUp(self): self.assertEqual(Matchday.objects.all().count(), 1) def test_parsed_player_stat_contains_all_foreign_keys(self): - self.assertEquals(type(self.first_player_stat), PlayerStatistics) - self.assertEquals(type(self.first_player_stat.player), Player) - self.assertEquals(self.first_player_stat.matchday.number, 0) - self.assertEquals(self.first_player_stat.matchday.season.number, 1) + self.assertEqual(type(self.first_player_stat), PlayerStatistics) + self.assertEqual(type(self.first_player_stat.player), Player) + self.assertEqual(self.first_player_stat.matchday.number, 0) + self.assertEqual(self.first_player_stat.matchday.season.number, 1) def test_parsed_player_stat_contains_all_fields(self): - self.assertEquals(3, len(self.player_stat_list)) - self.assertEquals('TW', self.first_player_stat.player.position) - self.assertEquals(159883060, self.first_player_stat.player.id) - self.assertEquals('Chrístos Tsigas', self.first_player_stat.player.name) - self.assertEquals('15', self.first_player_stat.strength) - self.assertEquals('47', self.first_player_stat.freshness) - self.assertEquals('29', self.first_player_stat.games_in_season) + self.assertEqual(3, len(self.player_stat_list)) + self.assertEqual('TW', self.first_player_stat.player.position) + self.assertEqual(159883060, self.first_player_stat.player.id) + self.assertEqual('Chrístos Tsigas', self.first_player_stat.player.name) + self.assertEqual('15', self.first_player_stat.strength) + self.assertEqual('47', self.first_player_stat.freshness) + self.assertEqual('29', self.first_player_stat.games_in_season) def test_parsed_player_stat_contains_correct_scored_goals(self): player_stat = self.player_stat_list[2] - self.assertEquals('4', player_stat.goals_in_season) + self.assertEqual('4', player_stat.goals_in_season) def test_parsed_player_stat_contains_correct_tacklings(self): - self.assertEquals('32', self.first_player_stat.won_tacklings_in_season) - self.assertEquals('36', self.first_player_stat.lost_tacklings_in_season) - self.assertEquals('37', self.first_player_stat.won_friendly_tacklings_in_season) - self.assertEquals('5', self.first_player_stat.lost_friendly_tacklings_in_season) + self.assertEqual('32', self.first_player_stat.won_tacklings_in_season) + self.assertEqual('36', self.first_player_stat.lost_tacklings_in_season) + self.assertEqual('37', self.first_player_stat.won_friendly_tacklings_in_season) + self.assertEqual('5', self.first_player_stat.lost_friendly_tacklings_in_season) def test_parsed_player_stat_contains_correct_cards_received(self): player_stat = self.player_stat_list[1] - self.assertEquals('3', player_stat.yellow_cards_in_season) - self.assertEquals('1', player_stat.red_cards_in_season) + self.assertEqual('3', player_stat.yellow_cards_in_season) + self.assertEqual('1', player_stat.red_cards_in_season) def test_parsed_player_stat_contains_correct_player_enhancement_data(self): - self.assertEquals('8599', self.first_player_stat.ep) - self.assertEquals('13227', self.first_player_stat.tp) - self.assertEquals('10422', self.first_player_stat.awp) + self.assertEqual('8599', self.first_player_stat.ep) + self.assertEqual('13227', self.first_player_stat.tp) + self.assertEqual('10422', self.first_player_stat.awp) def test_parsed_player_stat_contains_correct_equity(self): - self.assertEquals('16015782', self.first_player_stat.equity) + self.assertEqual('16015782', self.first_player_stat.equity) def test_parse_player_stat_should_return_same_instance_if_nothing_changes(self): self.parser.html_source = open(os.path.join(TESTDATA_PATH, 'player_statistics.html'), encoding='utf8') stat2 = self.parser.parse() self.assertEqual(self.player_stat_list, stat2) - self.assertEquals(Player.objects.all().count(), 3) + self.assertEqual(Player.objects.all().count(), 3) self.assertEqual(Matchday.objects.all().count(), 1) def test_parsed_contract_is_registered(self): - self.assertEquals(Contract.objects.all().count(), 3) + self.assertEqual(Contract.objects.all().count(), 3) diff --git a/core/tests/unit/parser/test_players_parser.py b/core/tests/unit/parser/test_players_parser.py index 7ac5786..04c212d 100644 --- a/core/tests/unit/parser/test_players_parser.py +++ b/core/tests/unit/parser/test_players_parser.py @@ -20,19 +20,19 @@ def setUp(self): self.first_player = self.player_list[0] def test_players_parser(self): - self.assertEquals(type(self.first_player), Player) - self.assertEquals(20, len(self.player_list)) - self.assertEquals(20, Player.objects.all().count()) + self.assertEqual(type(self.first_player), Player) + self.assertEqual(20, len(self.player_list)) + self.assertEqual(20, Player.objects.all().count()) def test_parsed_player_contains_all_fields(self): - self.assertEquals('Igor Vernon', self.first_player.name) - self.assertEquals('TW', self.first_player.position) - self.assertEquals(163739266, self.first_player.id) - self.assertEquals(29, self.matchday.season.number - self.first_player.birth_season.number) - self.assertEquals('Frankreich', str(self.first_player.nationality)) + self.assertEqual('Igor Vernon', self.first_player.name) + self.assertEqual('TW', self.first_player.position) + self.assertEqual(163739266, self.first_player.id) + self.assertEqual(29, self.matchday.season.number - self.first_player.birth_season.number) + self.assertEqual('Frankreich', str(self.first_player.nationality)) def test_parsed_player_has_contract_with_user(self): - self.assertEquals(1, len(Contract.objects.filter(player=self.first_player, user=self.user, sold_on_matchday=None))) + self.assertEqual(1, len(Contract.objects.filter(player=self.first_player, user=self.user, sold_on_matchday=None))) def test_sold_player_gets_according_attribute(self): testdata = open(os.path.join(TESTDATA_PATH, 'players_one_player_sold.html'), encoding='utf8') @@ -42,5 +42,5 @@ def test_sold_player_gets_according_attribute(self): sold_players = [c.player for c in Contract.objects.filter(sold_on_matchday__isnull=False)] - self.assertEquals(1, len(sold_players)) - self.assertEquals("Estaníslão Euklidio", sold_players[0].name) + self.assertEqual(1, len(sold_players)) + self.assertEqual("Estaníslão Euklidio", sold_players[0].name) diff --git a/core/tests/unit/parser/test_stadium_stand_statistics_parser.py b/core/tests/unit/parser/test_stadium_stand_statistics_parser.py index 382afee..fc228be 100644 --- a/core/tests/unit/parser/test_stadium_stand_statistics_parser.py +++ b/core/tests/unit/parser/test_stadium_stand_statistics_parser.py @@ -21,41 +21,41 @@ def setUp(self): self.stadium_stand_stats = self.parser.parse() def test_stadium_stand_stat_parser_north_stand(self): - self.assertEquals(type(self.stadium_stand_stats[0]), StadiumStandStatistics) - self.assertEquals(self.stadium_stand_stats[0].sector, 'N') - self.assertEquals(self.stadium_stand_stats[0].condition, '91.41') - self.assertEquals(self.stadium_stand_stats[0].visitors, '97') - self.assertEquals(self.stadium_stand_stats[0].ticket_price, '35') - self.assertEquals(self.stadium_stand_stats[0].level.capacity, '200') - self.assertEquals(self.stadium_stand_stats[0].level.has_roof, False) - self.assertEquals(self.stadium_stand_stats[0].level.has_seats, True) + self.assertEqual(type(self.stadium_stand_stats[0]), StadiumStandStatistics) + self.assertEqual(self.stadium_stand_stats[0].sector, 'N') + self.assertEqual(self.stadium_stand_stats[0].condition, '91.41') + self.assertEqual(self.stadium_stand_stats[0].visitors, '97') + self.assertEqual(self.stadium_stand_stats[0].ticket_price, '35') + self.assertEqual(self.stadium_stand_stats[0].level.capacity, '200') + self.assertEqual(self.stadium_stand_stats[0].level.has_roof, False) + self.assertEqual(self.stadium_stand_stats[0].level.has_seats, True) def test_stadium_stand_stat_parser_east_stand(self): - self.assertEquals(type(self.stadium_stand_stats[1]), StadiumStandStatistics) - self.assertEquals(self.stadium_stand_stats[1].sector, 'O') - self.assertEquals(self.stadium_stand_stats[1].condition, '94.02') - self.assertEquals(self.stadium_stand_stats[1].visitors, '99') - self.assertEquals(self.stadium_stand_stats[1].ticket_price, '20') - self.assertEquals(self.stadium_stand_stats[1].level.capacity, '100') - self.assertEquals(self.stadium_stand_stats[1].level.has_roof, False) - self.assertEquals(self.stadium_stand_stats[1].level.has_seats, False) + self.assertEqual(type(self.stadium_stand_stats[1]), StadiumStandStatistics) + self.assertEqual(self.stadium_stand_stats[1].sector, 'O') + self.assertEqual(self.stadium_stand_stats[1].condition, '94.02') + self.assertEqual(self.stadium_stand_stats[1].visitors, '99') + self.assertEqual(self.stadium_stand_stats[1].ticket_price, '20') + self.assertEqual(self.stadium_stand_stats[1].level.capacity, '100') + self.assertEqual(self.stadium_stand_stats[1].level.has_roof, False) + self.assertEqual(self.stadium_stand_stats[1].level.has_seats, False) def test_stadium_stand_stat_parser_south_stand(self): - self.assertEquals(type(self.stadium_stand_stats[2]), StadiumStandStatistics) - self.assertEquals(self.stadium_stand_stats[2].sector, 'S') - self.assertEquals(self.stadium_stand_stats[2].condition, '50.86') - self.assertEquals(self.stadium_stand_stats[2].visitors, '88') - self.assertEquals(self.stadium_stand_stats[2].ticket_price, '35') - self.assertEquals(self.stadium_stand_stats[2].level.capacity, '100') - self.assertEquals(self.stadium_stand_stats[2].level.has_roof, True) - self.assertEquals(self.stadium_stand_stats[2].level.has_seats, False) + self.assertEqual(type(self.stadium_stand_stats[2]), StadiumStandStatistics) + self.assertEqual(self.stadium_stand_stats[2].sector, 'S') + self.assertEqual(self.stadium_stand_stats[2].condition, '50.86') + self.assertEqual(self.stadium_stand_stats[2].visitors, '88') + self.assertEqual(self.stadium_stand_stats[2].ticket_price, '35') + self.assertEqual(self.stadium_stand_stats[2].level.capacity, '100') + self.assertEqual(self.stadium_stand_stats[2].level.has_roof, True) + self.assertEqual(self.stadium_stand_stats[2].level.has_seats, False) def test_stadium_stand_stat_parser_west_stand(self): - self.assertEquals(type(self.stadium_stand_stats[3]), StadiumStandStatistics) - self.assertEquals(self.stadium_stand_stats[3].sector, 'W') - self.assertEquals(self.stadium_stand_stats[3].condition, '94.02') - self.assertEquals(self.stadium_stand_stats[3].visitors, '99') - self.assertEquals(self.stadium_stand_stats[3].ticket_price, '40') - self.assertEquals(self.stadium_stand_stats[3].level.capacity, '100') - self.assertEquals(self.stadium_stand_stats[3].level.has_roof, True) - self.assertEquals(self.stadium_stand_stats[3].level.has_seats, True) + self.assertEqual(type(self.stadium_stand_stats[3]), StadiumStandStatistics) + self.assertEqual(self.stadium_stand_stats[3].sector, 'W') + self.assertEqual(self.stadium_stand_stats[3].condition, '94.02') + self.assertEqual(self.stadium_stand_stats[3].visitors, '99') + self.assertEqual(self.stadium_stand_stats[3].ticket_price, '40') + self.assertEqual(self.stadium_stand_stats[3].level.capacity, '100') + self.assertEqual(self.stadium_stand_stats[3].level.has_roof, True) + self.assertEqual(self.stadium_stand_stats[3].level.has_seats, True) diff --git a/core/tests/unit/parser/test_stadium_stand_statistics_parser_construction.py b/core/tests/unit/parser/test_stadium_stand_statistics_parser_construction.py index 8a343e1..e34261e 100644 --- a/core/tests/unit/parser/test_stadium_stand_statistics_parser_construction.py +++ b/core/tests/unit/parser/test_stadium_stand_statistics_parser_construction.py @@ -21,27 +21,27 @@ def setUp(self): self.stadium_stand_stats = self.parser.parse() def test_stadium_stand_stat_parser_north_stand_set_under_construction_after_match(self): - self.assertEquals(type(self.stadium_stand_stats[0]), StadiumStandStatistics) - self.assertEquals(self.stadium_stand_stats[0].sector, 'N') - self.assertEquals(self.stadium_stand_stats[0].condition, 100) - self.assertEquals(self.stadium_stand_stats[0].visitors, '200') - self.assertEquals(self.stadium_stand_stats[0].ticket_price, '35') - self.assertEquals(self.stadium_stand_stats[0].level.capacity, '200') - self.assertEquals(self.stadium_stand_stats[0].level.has_roof, True) - self.assertEquals(self.stadium_stand_stats[0].level.has_seats, True) + self.assertEqual(type(self.stadium_stand_stats[0]), StadiumStandStatistics) + self.assertEqual(self.stadium_stand_stats[0].sector, 'N') + self.assertEqual(self.stadium_stand_stats[0].condition, 100) + self.assertEqual(self.stadium_stand_stats[0].visitors, '200') + self.assertEqual(self.stadium_stand_stats[0].ticket_price, '35') + self.assertEqual(self.stadium_stand_stats[0].level.capacity, '200') + self.assertEqual(self.stadium_stand_stats[0].level.has_roof, True) + self.assertEqual(self.stadium_stand_stats[0].level.has_seats, True) def test_stadium_stand_stat_parser_east_set_under_construction_before_match(self): - self.assertEquals(self.stadium_stand_stats[1], None) + self.assertEqual(self.stadium_stand_stats[1], None) def test_stadium_stand_stat_parser_south_stand_set_in_repair_after_match(self): - self.assertEquals(type(self.stadium_stand_stats[2]), StadiumStandStatistics) - self.assertEquals(self.stadium_stand_stats[2].sector, 'S') - self.assertEquals(self.stadium_stand_stats[2].condition, 100) - self.assertEquals(self.stadium_stand_stats[2].visitors, '398') - self.assertEquals(self.stadium_stand_stats[2].ticket_price, '35') - self.assertEquals(self.stadium_stand_stats[2].level.capacity, '400') - self.assertEquals(self.stadium_stand_stats[2].level.has_roof, True) - self.assertEquals(self.stadium_stand_stats[2].level.has_seats, False) + self.assertEqual(type(self.stadium_stand_stats[2]), StadiumStandStatistics) + self.assertEqual(self.stadium_stand_stats[2].sector, 'S') + self.assertEqual(self.stadium_stand_stats[2].condition, 100) + self.assertEqual(self.stadium_stand_stats[2].visitors, '398') + self.assertEqual(self.stadium_stand_stats[2].ticket_price, '35') + self.assertEqual(self.stadium_stand_stats[2].level.capacity, '400') + self.assertEqual(self.stadium_stand_stats[2].level.has_roof, True) + self.assertEqual(self.stadium_stand_stats[2].level.has_seats, False) def test_stadium_stand_stat_parser_west_set_in_repair_before_match(self): - self.assertEquals(self.stadium_stand_stats[3], None) + self.assertEqual(self.stadium_stand_stats[3], None) diff --git a/core/tests/unit/parser/test_stadium_statistics_parser.py b/core/tests/unit/parser/test_stadium_statistics_parser.py index 58db580..df41fdb 100644 --- a/core/tests/unit/parser/test_stadium_statistics_parser.py +++ b/core/tests/unit/parser/test_stadium_statistics_parser.py @@ -22,19 +22,19 @@ def setUp(self): def test_stadium_environment_parser_contains_correct_types(self): stadium_stat = self.parser.parse() - self.assertEquals(type(stadium_stat), MatchStadiumStatistics) - self.assertEquals(stadium_stat.match, self.match2) - self.assertEquals(type(stadium_stat.level), StadiumLevel) - self.assertEquals(type(stadium_stat.level.light), StadiumLevelItem) - self.assertEquals(type(stadium_stat.level.screen), StadiumLevelItem) - self.assertEquals(type(stadium_stat.level.security), StadiumLevelItem) - self.assertEquals(type(stadium_stat.level.parking), StadiumLevelItem) + self.assertEqual(type(stadium_stat), MatchStadiumStatistics) + self.assertEqual(stadium_stat.match, self.match2) + self.assertEqual(type(stadium_stat.level), StadiumLevel) + self.assertEqual(type(stadium_stat.level.light), StadiumLevelItem) + self.assertEqual(type(stadium_stat.level.screen), StadiumLevelItem) + self.assertEqual(type(stadium_stat.level.security), StadiumLevelItem) + self.assertEqual(type(stadium_stat.level.parking), StadiumLevelItem) def test_stadium_environment_parser_contains_correct_light_data(self): stadium_stat = self.parser.parse() - self.assertEquals(stadium_stat.level.light.current_level, '1') - self.assertEquals(stadium_stat.level.light.value, '20') - self.assertEquals(stadium_stat.level.light.daily_costs, '10') + self.assertEqual(stadium_stat.level.light.current_level, '1') + self.assertEqual(stadium_stat.level.light.value, '20') + self.assertEqual(stadium_stat.level.light.daily_costs, '10') def test_stadium_environment_parser_takes_old_screen_data_while_in_construction_if_older_stat_exists(self): matchday1 = MatchdayFactory.create(number=1) @@ -43,24 +43,24 @@ def test_stadium_environment_parser_takes_old_screen_data_while_in_construction_ MatchStadiumStatisticsFactory.create(match=match1, level=last_level) stadium_stat = self.parser.parse() - self.assertEquals(stadium_stat.level.screen.current_level, 0) - self.assertEquals(stadium_stat.level.screen.value, 0) - self.assertEquals(stadium_stat.level.screen.daily_costs, 0) + self.assertEqual(stadium_stat.level.screen.current_level, 0) + self.assertEqual(stadium_stat.level.screen.value, 0) + self.assertEqual(stadium_stat.level.screen.daily_costs, 0) def test_stadium_environment_parser_takes_new_screen_data_while_in_construction_but_no_older_stat_exists(self): stadium_stat = self.parser.parse() - self.assertEquals(stadium_stat.level.screen.current_level, '1') - self.assertEquals(stadium_stat.level.screen.value, '500000') - self.assertEquals(stadium_stat.level.screen.daily_costs, '7500') + self.assertEqual(stadium_stat.level.screen.current_level, '1') + self.assertEqual(stadium_stat.level.screen.value, '500000') + self.assertEqual(stadium_stat.level.screen.daily_costs, '7500') def test_stadium_environment_parser_contains_correct_security_data(self): stadium_stat = self.parser.parse() - self.assertEquals(stadium_stat.level.security.current_level, '2') - self.assertEquals(stadium_stat.level.security.value, '2000') - self.assertEquals(stadium_stat.level.security.daily_costs, '150') + self.assertEqual(stadium_stat.level.security.current_level, '2') + self.assertEqual(stadium_stat.level.security.value, '2000') + self.assertEqual(stadium_stat.level.security.daily_costs, '150') def test_stadium_environment_parser_contains_correct_parking_data(self): stadium_stat = self.parser.parse() - self.assertEquals(stadium_stat.level.parking.current_level, '3') - self.assertEquals(stadium_stat.level.parking.value, '42') - self.assertEquals(stadium_stat.level.parking.daily_costs, '42') + self.assertEqual(stadium_stat.level.parking.current_level, '3') + self.assertEqual(stadium_stat.level.parking.value, '42') + self.assertEqual(stadium_stat.level.parking.daily_costs, '42') diff --git a/core/tests/unit/parser/test_won_by_default_match_row_parser.py b/core/tests/unit/parser/test_won_by_default_match_row_parser.py index d0c6551..32f249d 100644 --- a/core/tests/unit/parser/test_won_by_default_match_row_parser.py +++ b/core/tests/unit/parser/test_won_by_default_match_row_parser.py @@ -23,32 +23,32 @@ def setUp(self): self.match_stat = self.parser.parse() def test_match_parser_general_informations(self): - self.assertEquals(type(self.match_stat), Match) - self.assertEquals(self.match_stat.matchday.number, '8') - self.assertEquals(self.match_stat.user, self.user) - self.assertEquals(self.match_stat.match_type, 'L') - self.assertEquals(self.match_stat.venue, '') - self.assertEquals(self.match_stat.is_in_future, False) + self.assertEqual(type(self.match_stat), Match) + self.assertEqual(self.match_stat.matchday.number, '8') + self.assertEqual(self.match_stat.user, self.user) + self.assertEqual(self.match_stat.match_type, 'L') + self.assertEqual(self.match_stat.venue, '') + self.assertEqual(self.match_stat.is_in_future, False) def test_match_home_team_statistics(self): - self.assertEquals(type(self.match_stat.home_team_statistics), MatchTeamStatistics) - self.assertEquals(self.match_stat.home_team_statistics.score, '3') - self.assertEquals(self.match_stat.home_team_statistics.team_name, 'BSC Wittenau') - self.assertEquals(self.match_stat.home_team_statistics.strength, '58') - self.assertEquals(self.match_stat.home_team_statistics.ball_possession, 100) - self.assertEquals(self.match_stat.home_team_statistics.chances, 0) - self.assertEquals(self.match_stat.home_team_statistics.yellow_cards, 0) - self.assertEquals(self.match_stat.home_team_statistics.red_cards, 0) + self.assertEqual(type(self.match_stat.home_team_statistics), MatchTeamStatistics) + self.assertEqual(self.match_stat.home_team_statistics.score, '3') + self.assertEqual(self.match_stat.home_team_statistics.team_name, 'BSC Wittenau') + self.assertEqual(self.match_stat.home_team_statistics.strength, '58') + self.assertEqual(self.match_stat.home_team_statistics.ball_possession, 100) + self.assertEqual(self.match_stat.home_team_statistics.chances, 0) + self.assertEqual(self.match_stat.home_team_statistics.yellow_cards, 0) + self.assertEqual(self.match_stat.home_team_statistics.red_cards, 0) def test_match_guest_team_statistics(self): - self.assertEquals(type(self.match_stat.guest_team_statistics), MatchTeamStatistics) - self.assertEquals(self.match_stat.guest_team_statistics.score, '0') - self.assertEquals(self.match_stat.guest_team_statistics.team_name, 'NicNock') - self.assertEquals(self.match_stat.guest_team_statistics.strength, '0') - self.assertEquals(self.match_stat.guest_team_statistics.ball_possession, 0) - self.assertEquals(self.match_stat.guest_team_statistics.chances, 0) - self.assertEquals(self.match_stat.guest_team_statistics.yellow_cards, 0) - self.assertEquals(self.match_stat.guest_team_statistics.red_cards, 0) + self.assertEqual(type(self.match_stat.guest_team_statistics), MatchTeamStatistics) + self.assertEqual(self.match_stat.guest_team_statistics.score, '0') + self.assertEqual(self.match_stat.guest_team_statistics.team_name, 'NicNock') + self.assertEqual(self.match_stat.guest_team_statistics.strength, '0') + self.assertEqual(self.match_stat.guest_team_statistics.ball_possession, 0) + self.assertEqual(self.match_stat.guest_team_statistics.chances, 0) + self.assertEqual(self.match_stat.guest_team_statistics.yellow_cards, 0) + self.assertEqual(self.match_stat.guest_team_statistics.red_cards, 0) def test_match_gets_updated_on_parsing_again(self): testdata = open(os.path.join(TESTDATA_PATH, 'home_match_row_won_by_default_2.html'), encoding='utf8') @@ -58,9 +58,9 @@ def test_match_gets_updated_on_parsing_again(self): self.parser = WonByDefaultMatchRowParser(soup, self.user) match_stat2 = self.parser.parse() - self.assertEquals(self.match_stat.id, match_stat2.id) - self.assertEquals(self.match_stat.home_team_statistics.id, match_stat2.home_team_statistics.id) - self.assertEquals(self.match_stat.guest_team_statistics.id, match_stat2.guest_team_statistics.id) - self.assertEquals(match_stat2.home_team_statistics.strength, '66') - self.assertEquals(match_stat2.guest_team_statistics.strength, '1') - self.assertEquals(2, MatchTeamStatistics.objects.all().count()) + self.assertEqual(self.match_stat.id, match_stat2.id) + self.assertEqual(self.match_stat.home_team_statistics.id, match_stat2.home_team_statistics.id) + self.assertEqual(self.match_stat.guest_team_statistics.id, match_stat2.guest_team_statistics.id) + self.assertEqual(match_stat2.home_team_statistics.strength, '66') + self.assertEqual(match_stat2.guest_team_statistics.strength, '1') + self.assertEqual(2, MatchTeamStatistics.objects.all().count()) diff --git a/core/tests/unit/test_core_models.py b/core/tests/unit/test_core_models.py index c057221..ef5dace 100644 --- a/core/tests/unit/test_core_models.py +++ b/core/tests/unit/test_core_models.py @@ -12,19 +12,19 @@ class CreateCoreModelsTest(TestCase): def test_create_season(self): s = SeasonFactory.create(number=2) self.assertIsNotNone(s) - self.assertEquals(s.number, 2) + self.assertEqual(s.number, 2) def test_create_quarter(self): q = QuarterFactory.create() self.assertIsNotNone(q) - self.assertEquals(q.season.number, 1) - self.assertEquals(q.quarter, 1) + self.assertEqual(q.season.number, 1) + self.assertEqual(q.quarter, 1) def test_create_matchday(self): m = MatchdayFactory.create() self.assertIsNotNone(m) - self.assertEquals(m.season.number, 1) - self.assertEquals(m.number, 0) + self.assertEqual(m.season.number, 1) + self.assertEqual(m.number, 0) def test_get_current_matchday_default(self): MatchdayFactory.create(number=1) @@ -63,39 +63,39 @@ def test_get_current_matchday_from_matches(self): def test_matchday_order_desc_by_number(self): MatchdayFactory.create(number=1) MatchdayFactory.create(number=2) - self.assertEquals(Matchday.objects.all()[0].number, 2) + self.assertEqual(Matchday.objects.all()[0].number, 2) def test_matchday_order_desc_by_season(self): s = SeasonFactory.create(number=2) MatchdayFactory.create() MatchdayFactory.create(season=s) - self.assertEquals(Matchday.objects.all()[0].season.number, 2) + self.assertEqual(Matchday.objects.all()[0].season.number, 2) def test_create_player_statistics(self): st = PlayerStatisticsFactory.create() - self.assertEquals(st.ep, 2) - self.assertEquals(st.tp, 5) - self.assertEquals(st.awp, 3) - self.assertEquals(st.strength, 1) - self.assertEquals(st.freshness, 4) - self.assertEquals(st.games_in_season, 0) - self.assertEquals(st.goals_in_season, 0) - self.assertEquals(st.won_tacklings_in_season, 0) - self.assertEquals(st.lost_tacklings_in_season, 0) - self.assertEquals(st.won_friendly_tacklings_in_season, 0) - self.assertEquals(st.lost_friendly_tacklings_in_season, 0) - self.assertEquals(st.yellow_cards_in_season, 0) - self.assertEquals(st.red_cards_in_season, 0) - self.assertEquals(st.equity, 0) + self.assertEqual(st.ep, 2) + self.assertEqual(st.tp, 5) + self.assertEqual(st.awp, 3) + self.assertEqual(st.strength, 1) + self.assertEqual(st.freshness, 4) + self.assertEqual(st.games_in_season, 0) + self.assertEqual(st.goals_in_season, 0) + self.assertEqual(st.won_tacklings_in_season, 0) + self.assertEqual(st.lost_tacklings_in_season, 0) + self.assertEqual(st.won_friendly_tacklings_in_season, 0) + self.assertEqual(st.lost_friendly_tacklings_in_season, 0) + self.assertEqual(st.yellow_cards_in_season, 0) + self.assertEqual(st.red_cards_in_season, 0) + self.assertEqual(st.equity, 0) def test_create_player(self): c = CountryFactory.create() p = PlayerFactory.create(position=1, name='tw1', nationality=c) self.assertIsNotNone(p) - self.assertEquals(p.position, 1) - self.assertEquals(p.name, 'tw1') + self.assertEqual(p.position, 1) + self.assertEqual(p.name, 'tw1') self.assertTrue(p.nationality is not None) - self.assertEquals(p.birth_season.number, 1) + self.assertEqual(p.birth_season.number, 1) def test_create_contract(self): c = ContractFactory.create() diff --git a/core/tests/unit/views/test_ofm_finances_charts_views.py b/core/tests/unit/views/test_ofm_finances_charts_views.py index 0434a8c..892022f 100644 --- a/core/tests/unit/views/test_ofm_finances_charts_views.py +++ b/core/tests/unit/views/test_ofm_finances_charts_views.py @@ -23,7 +23,7 @@ def test_finance_balance_chart_json(self): self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) self.assertTrue('series' in returned_json_data) - self.assertEquals('Kontostand', returned_json_data['series'][0]['name']) + self.assertEqual('Kontostand', returned_json_data['series'][0]['name']) self.assertTrue('data' in returned_json_data['series'][0]) self.assertTrue('categories' in returned_json_data) @@ -32,7 +32,7 @@ def test_finance_income_chart_json(self): self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) self.assertTrue('series' in returned_json_data) - self.assertEquals('Ticketeinnahmen Liga', returned_json_data['series'][0]['name']) + self.assertEqual('Ticketeinnahmen Liga', returned_json_data['series'][0]['name']) self.assertTrue('data' in returned_json_data['series'][0]) self.assertTrue('categories' in returned_json_data) @@ -41,6 +41,6 @@ def test_finance_expenses_chart_json(self): self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) self.assertTrue('series' in returned_json_data) - self.assertEquals('Spielergehalt', returned_json_data['series'][0]['name']) + self.assertEqual('Spielergehalt', returned_json_data['series'][0]['name']) self.assertTrue('data' in returned_json_data['series'][0]) self.assertTrue('categories' in returned_json_data) diff --git a/core/tests/unit/views/test_ofm_finances_view.py b/core/tests/unit/views/test_ofm_finances_view.py index 9602af7..ff4baac 100644 --- a/core/tests/unit/views/test_ofm_finances_view.py +++ b/core/tests/unit/views/test_ofm_finances_view.py @@ -27,18 +27,18 @@ def test_user_can_choose_between_matchdays(self): response = self.client.get(reverse('core:ofm:finance_overview')) self.assertEqual(response.status_code, 200) - self.assertEquals(self.next_matchday, response.context_data['matchdays'][0]) - self.assertEquals(self.matchday, response.context_data['matchdays'][1]) + self.assertEqual(self.next_matchday, response.context_data['matchdays'][0]) + self.assertEqual(self.matchday, response.context_data['matchdays'][1]) def test_user_can_see_his_latest_finances_when_given_no_matchday(self): response = self.client.get(reverse('core:ofm:finances_json')) self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) - self.assertEquals(len(returned_json_data), 1) - self.assertEquals(returned_json_data[0]['account_balance'], 2000) - self.assertEquals(returned_json_data[0]['income_visitors_league'], 200) - self.assertEquals(returned_json_data[0]['expenses_player_salaries'], -200) + self.assertEqual(len(returned_json_data), 1) + self.assertEqual(returned_json_data[0]['account_balance'], 2000) + self.assertEqual(returned_json_data[0]['income_visitors_league'], 200) + self.assertEqual(returned_json_data[0]['expenses_player_salaries'], -200) def test_user_can_see_his_finances_diff_when_given_both_matchdays(self): third_matchday = MatchdayFactory.create(number=self.matchday.number + 2) @@ -54,13 +54,13 @@ def test_user_can_see_his_finances_diff_when_given_both_matchdays(self): self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) - self.assertEquals(len(returned_json_data), 1) - self.assertEquals(returned_json_data[0]['account_balance'], 2500) - self.assertEquals(returned_json_data[0]['balance'], 150) - self.assertEquals(returned_json_data[0]['sum_income'], 400) - self.assertEquals(returned_json_data[0]['sum_expenses'], -250) - self.assertEquals(returned_json_data[0]['income_visitors_league'], 150) - self.assertEquals(returned_json_data[0]['expenses_player_salaries'], -150) + self.assertEqual(len(returned_json_data), 1) + self.assertEqual(returned_json_data[0]['account_balance'], 2500) + self.assertEqual(returned_json_data[0]['balance'], 150) + self.assertEqual(returned_json_data[0]['sum_income'], 400) + self.assertEqual(returned_json_data[0]['sum_expenses'], -250) + self.assertEqual(returned_json_data[0]['income_visitors_league'], 150) + self.assertEqual(returned_json_data[0]['expenses_player_salaries'], -150) def test_user_can_see_his_finances_diff_when_given_only_newer_matchday(self): third_matchday = MatchdayFactory.create(number=self.matchday.number + 2) @@ -74,10 +74,10 @@ def test_user_can_see_his_finances_diff_when_given_only_newer_matchday(self): self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) - self.assertEquals(len(returned_json_data), 1) - self.assertEquals(returned_json_data[0]['account_balance'], 2500) - self.assertEquals(returned_json_data[0]['balance'], 0) - self.assertEquals(returned_json_data[0]['sum_income'], 250) - self.assertEquals(returned_json_data[0]['sum_expenses'], -250) - self.assertEquals(returned_json_data[0]['income_visitors_league'], 250) - self.assertEquals(returned_json_data[0]['expenses_player_salaries'], -250) + self.assertEqual(len(returned_json_data), 1) + self.assertEqual(returned_json_data[0]['account_balance'], 2500) + self.assertEqual(returned_json_data[0]['balance'], 0) + self.assertEqual(returned_json_data[0]['sum_income'], 250) + self.assertEqual(returned_json_data[0]['sum_expenses'], -250) + self.assertEqual(returned_json_data[0]['income_visitors_league'], 250) + self.assertEqual(returned_json_data[0]['expenses_player_salaries'], -250) diff --git a/core/tests/unit/views/test_ofm_matches_view.py b/core/tests/unit/views/test_ofm_matches_view.py index e338f15..70b3249 100644 --- a/core/tests/unit/views/test_ofm_matches_view.py +++ b/core/tests/unit/views/test_ofm_matches_view.py @@ -26,7 +26,7 @@ def test_user_can_see_his_latest_matches_when_given_no_season(self): self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) - self.assertEquals(len(returned_json_data), 1) + self.assertEqual(len(returned_json_data), 1) self.assertTrue('Springfield Isotopes' in returned_json_data[0]['home_team']) self.assertTrue('Springfield Isotopes' in returned_json_data[0]['guest_team']) @@ -37,6 +37,6 @@ def test_user_can_see_matches_summary(self): response = self.client.get(reverse('core:ofm:matches_summary_json')) self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) - self.assertEquals(0, returned_json_data['matches_won']) - self.assertEquals(1, returned_json_data['matches_draw']) - self.assertEquals(0, returned_json_data['matches_lost']) + self.assertEqual(0, returned_json_data['matches_won']) + self.assertEqual(1, returned_json_data['matches_draw']) + self.assertEqual(0, returned_json_data['matches_lost']) diff --git a/core/tests/unit/views/test_ofm_player_detail_view.py b/core/tests/unit/views/test_ofm_player_detail_view.py index 5608742..526738d 100644 --- a/core/tests/unit/views/test_ofm_player_detail_view.py +++ b/core/tests/unit/views/test_ofm_player_detail_view.py @@ -46,12 +46,12 @@ def test_player_chart_json(self): returned_json_data = json.loads(response.content.decode('utf-8')) self.assertTrue('series' in returned_json_data) - self.assertEquals('AWP', returned_json_data['series'][0]['name']) + self.assertEqual('AWP', returned_json_data['series'][0]['name']) self.assertTrue('data' in returned_json_data['series'][0]) - self.assertEquals('AWP-Grenze: 2', returned_json_data['series'][1]['name']) + self.assertEqual('AWP-Grenze: 2', returned_json_data['series'][1]['name']) self.assertTrue('data' in returned_json_data['series'][1]) - self.assertEquals([1000], returned_json_data['series'][1]['data']) + self.assertEqual([1000], returned_json_data['series'][1]['data']) self.assertTrue('categories' in returned_json_data) @@ -68,12 +68,12 @@ def test_player_chart_shows_awp_boundaries_which_are_only_greater_than_my_streng returned_json_data = json.loads(response.content.decode('utf-8')) self.assertTrue('series' in returned_json_data) - self.assertEquals('AWP', returned_json_data['series'][0]['name']) + self.assertEqual('AWP', returned_json_data['series'][0]['name']) self.assertTrue('data' in returned_json_data['series'][0]) - self.assertEquals('AWP-Grenze: 4', returned_json_data['series'][1]['name']) + self.assertEqual('AWP-Grenze: 4', returned_json_data['series'][1]['name']) self.assertTrue('data' in returned_json_data['series'][1]) - self.assertEquals([4000], returned_json_data['series'][1]['data']) + self.assertEqual([4000], returned_json_data['series'][1]['data']) def test_player_chart_shows_reached_but_not_promoted_awp_boundary(self): PlayerStatisticsFactory.create(player=self.player, matchday=self.matchday, strength=2, awp=2800) @@ -90,16 +90,16 @@ def test_player_chart_shows_reached_but_not_promoted_awp_boundary(self): returned_json_data = json.loads(response.content.decode('utf-8')) self.assertTrue('series' in returned_json_data) - self.assertEquals('AWP', returned_json_data['series'][0]['name']) + self.assertEqual('AWP', returned_json_data['series'][0]['name']) self.assertTrue('data' in returned_json_data['series'][0]) - self.assertEquals('AWP-Grenze: 3', returned_json_data['series'][1]['name']) + self.assertEqual('AWP-Grenze: 3', returned_json_data['series'][1]['name']) self.assertTrue('data' in returned_json_data['series'][1]) - self.assertEquals([3000] * 2, returned_json_data['series'][1]['data']) + self.assertEqual([3000] * 2, returned_json_data['series'][1]['data']) - self.assertEquals('AWP-Grenze: 4', returned_json_data['series'][2]['name']) + self.assertEqual('AWP-Grenze: 4', returned_json_data['series'][2]['name']) self.assertTrue('data' in returned_json_data['series'][2]) - self.assertEquals([4000] * 2, returned_json_data['series'][2]['data']) + self.assertEqual([4000] * 2, returned_json_data['series'][2]['data']) def test_player_chart_does_not_show_boundary_if_promoted(self): PlayerStatisticsFactory.create(player=self.player, matchday=self.matchday, strength=2, awp=2800) @@ -120,12 +120,12 @@ def test_player_chart_does_not_show_boundary_if_promoted(self): returned_json_data = json.loads(response.content.decode('utf-8')) self.assertTrue('series' in returned_json_data) - self.assertEquals('AWP', returned_json_data['series'][0]['name']) + self.assertEqual('AWP', returned_json_data['series'][0]['name']) self.assertTrue('data' in returned_json_data['series'][0]) - self.assertEquals('AWP-Grenze: 4', returned_json_data['series'][1]['name']) + self.assertEqual('AWP-Grenze: 4', returned_json_data['series'][1]['name']) self.assertTrue('data' in returned_json_data['series'][1]) - self.assertEquals([3800, 4000], returned_json_data['series'][1]['data']) + self.assertEqual([3800, 4000], returned_json_data['series'][1]['data']) def test_player_chart_shows_different_awp_boundaries(self): matchday_9 = MatchdayFactory.create(number=9) @@ -144,9 +144,9 @@ def test_player_chart_shows_different_awp_boundaries(self): returned_json_data = json.loads(response.content.decode('utf-8')) self.assertTrue('series' in returned_json_data) - self.assertEquals('AWP', returned_json_data['series'][0]['name']) + self.assertEqual('AWP', returned_json_data['series'][0]['name']) self.assertTrue('data' in returned_json_data['series'][0]) - self.assertEquals('AWP-Grenze: 2', returned_json_data['series'][1]['name']) + self.assertEqual('AWP-Grenze: 2', returned_json_data['series'][1]['name']) self.assertTrue('data' in returned_json_data['series'][1]) - self.assertEquals([2000, 3000], returned_json_data['series'][1]['data']) + self.assertEqual([2000, 3000], returned_json_data['series'][1]['data']) diff --git a/core/tests/unit/views/test_ofm_player_statistics_view.py b/core/tests/unit/views/test_ofm_player_statistics_view.py index d93dfe8..ad96188 100644 --- a/core/tests/unit/views/test_ofm_player_statistics_view.py +++ b/core/tests/unit/views/test_ofm_player_statistics_view.py @@ -31,22 +31,22 @@ def test_user_can_choose_between_matchdays(self): response = self.client.get(reverse('core:ofm:player_statistics')) self.assertEqual(response.status_code, 200) - self.assertEquals(self.second_matchday, response.context_data['matchdays'][0]) - self.assertEquals(self.matchday, response.context_data['matchdays'][1]) + self.assertEqual(self.second_matchday, response.context_data['matchdays'][0]) + self.assertEqual(self.matchday, response.context_data['matchdays'][1]) def test_user_can_see_his_latest_player_statistics_total_when_given_no_matchday(self): response = self.client.get(reverse('core:ofm:player_statistics_json')) self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) - self.assertEquals(len(returned_json_data), 1) - self.assertEquals(returned_json_data[0]['position'], 'TW') - self.assertEquals(returned_json_data[0]['name'], 'Martin Adomeit') - self.assertEquals(returned_json_data[0]['ep'], 3) - self.assertEquals(returned_json_data[0]['tp'], 6) - self.assertEquals(returned_json_data[0]['awp'], 4) - self.assertEquals(returned_json_data[0]['strength'], 1) - self.assertEquals(returned_json_data[0]['freshness'], 5) + self.assertEqual(len(returned_json_data), 1) + self.assertEqual(returned_json_data[0]['position'], 'TW') + self.assertEqual(returned_json_data[0]['name'], 'Martin Adomeit') + self.assertEqual(returned_json_data[0]['ep'], 3) + self.assertEqual(returned_json_data[0]['tp'], 6) + self.assertEqual(returned_json_data[0]['awp'], 4) + self.assertEqual(returned_json_data[0]['strength'], 1) + self.assertEqual(returned_json_data[0]['freshness'], 5) def test_user_can_see_his_player_statistics_diff_when_given_both_matchdays(self): third_matchday = MatchdayFactory.create(number=self.matchday.number + 2) @@ -60,13 +60,13 @@ def test_user_can_see_his_player_statistics_diff_when_given_both_matchdays(self) }) returned_json_data = json.loads(response.content.decode('utf-8')) - self.assertEquals(returned_json_data[0]['position'], 'TW') - self.assertEquals(returned_json_data[0]['name'], 'Martin Adomeit') - self.assertEquals(returned_json_data[0]['ep'], 10) - self.assertEquals(returned_json_data[0]['tp'], 10) - self.assertEquals(returned_json_data[0]['awp'], 10) - self.assertEquals(returned_json_data[0]['strength'], 0) - self.assertEquals(returned_json_data[0]['freshness'], 10) + self.assertEqual(returned_json_data[0]['position'], 'TW') + self.assertEqual(returned_json_data[0]['name'], 'Martin Adomeit') + self.assertEqual(returned_json_data[0]['ep'], 10) + self.assertEqual(returned_json_data[0]['tp'], 10) + self.assertEqual(returned_json_data[0]['awp'], 10) + self.assertEqual(returned_json_data[0]['strength'], 0) + self.assertEqual(returned_json_data[0]['freshness'], 10) def test_user_can_see_his_player_statistics_diff_when_given_only_newer_matchday(self): third_matchday = MatchdayFactory.create(number=self.matchday.number + 2) @@ -78,13 +78,13 @@ def test_user_can_see_his_player_statistics_diff_when_given_only_newer_matchday( }) returned_json_data = json.loads(response.content.decode('utf-8')) - self.assertEquals(returned_json_data[0]['position'], 'TW') - self.assertEquals(returned_json_data[0]['name'], 'Martin Adomeit') - self.assertEquals(returned_json_data[0]['ep'], 12) - self.assertEquals(returned_json_data[0]['tp'], 15) - self.assertEquals(returned_json_data[0]['awp'], 13) - self.assertEquals(returned_json_data[0]['strength'], 1) - self.assertEquals(returned_json_data[0]['freshness'], 14) + self.assertEqual(returned_json_data[0]['position'], 'TW') + self.assertEqual(returned_json_data[0]['name'], 'Martin Adomeit') + self.assertEqual(returned_json_data[0]['ep'], 12) + self.assertEqual(returned_json_data[0]['tp'], 15) + self.assertEqual(returned_json_data[0]['awp'], 13) + self.assertEqual(returned_json_data[0]['strength'], 1) + self.assertEqual(returned_json_data[0]['freshness'], 14) def test_user_can_see_players_diff_to_next_awp_boundary_given_no_matchday(self): awp_boundaries = AwpBoundaries.get_or_create_from_matchday(self.matchday) @@ -93,7 +93,7 @@ def test_user_can_see_players_diff_to_next_awp_boundary_given_no_matchday(self): response = self.client.get(reverse('core:ofm:player_statistics_json')) returned_json_data = json.loads(response.content.decode('utf-8')) - self.assertEquals(returned_json_data[0]['awp_to_next_bound'], 16) + self.assertEqual(returned_json_data[0]['awp_to_next_bound'], 16) def test_user_can_see_players_diff_to_next_awp_boundary_given_matchdays(self): awp_boundaries = AwpBoundaries.get_or_create_from_matchday(self.matchday) @@ -107,7 +107,7 @@ def test_user_can_see_players_diff_to_next_awp_boundary_given_matchdays(self): }) returned_json_data = json.loads(response.content.decode('utf-8')) - self.assertEquals(returned_json_data[0]['awp_to_next_bound'], 16) + self.assertEqual(returned_json_data[0]['awp_to_next_bound'], 16) def test_player_leaves_team_shows_only_older_player_data(self): player2 = PlayerFactory.create(name="Tricia McMillan") @@ -123,13 +123,13 @@ def test_player_leaves_team_shows_only_older_player_data(self): }) returned_json_data = json.loads(response.content.decode('utf-8')) - self.assertEquals(len(returned_json_data), 1) - self.assertEquals(returned_json_data[0]['position'], self.player.position) - self.assertEquals(returned_json_data[0]['name'], 'Martin Adomeit') - self.assertEquals(returned_json_data[0]['ep'], 1) - self.assertEquals(returned_json_data[0]['tp'], 1) - self.assertEquals(returned_json_data[0]['awp'], 1) - self.assertEquals(returned_json_data[0]['freshness'], 1) + self.assertEqual(len(returned_json_data), 1) + self.assertEqual(returned_json_data[0]['position'], self.player.position) + self.assertEqual(returned_json_data[0]['name'], 'Martin Adomeit') + self.assertEqual(returned_json_data[0]['ep'], 1) + self.assertEqual(returned_json_data[0]['tp'], 1) + self.assertEqual(returned_json_data[0]['awp'], 1) + self.assertEqual(returned_json_data[0]['freshness'], 1) def test_player_joins_team_shows_only_older_player_data(self): player2 = PlayerFactory.create(name="Tricia McMillan") @@ -146,10 +146,10 @@ def test_player_joins_team_shows_only_older_player_data(self): }) returned_json_data = json.loads(response.content.decode('utf-8')) - self.assertEquals(len(returned_json_data), 1) - self.assertEquals(returned_json_data[0]['position'], self.player.position) - self.assertEquals(returned_json_data[0]['name'], 'Martin Adomeit') - self.assertEquals(returned_json_data[0]['ep'], 1) - self.assertEquals(returned_json_data[0]['tp'], 1) - self.assertEquals(returned_json_data[0]['awp'], 1) - self.assertEquals(returned_json_data[0]['freshness'], 1) + self.assertEqual(len(returned_json_data), 1) + self.assertEqual(returned_json_data[0]['position'], self.player.position) + self.assertEqual(returned_json_data[0]['name'], 'Martin Adomeit') + self.assertEqual(returned_json_data[0]['ep'], 1) + self.assertEqual(returned_json_data[0]['tp'], 1) + self.assertEqual(returned_json_data[0]['awp'], 1) + self.assertEqual(returned_json_data[0]['freshness'], 1) diff --git a/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py b/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py index cde8b05..5a08a86 100644 --- a/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py +++ b/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py @@ -43,11 +43,11 @@ def test_finance_balance_chart_json(self): self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) self.assertTrue('series' in returned_json_data) - self.assertEquals('Kapazität', returned_json_data['series'][0]['name']) - self.assertEquals('Zuschauer', returned_json_data['series'][1]['name']) - self.assertEquals('Ticketpreis', returned_json_data['series'][2]['name']) - self.assertEquals('Zustand', returned_json_data['series'][3]['name']) - self.assertEquals('Gemittelte Stärke der Mannschaften', returned_json_data['series'][4]['name']) + self.assertEqual('Kapazität', returned_json_data['series'][0]['name']) + self.assertEqual('Zuschauer', returned_json_data['series'][1]['name']) + self.assertEqual('Ticketpreis', returned_json_data['series'][2]['name']) + self.assertEqual('Zustand', returned_json_data['series'][3]['name']) + self.assertEqual('Gemittelte Stärke der Mannschaften', returned_json_data['series'][4]['name']) self.assertTrue('data' in returned_json_data['series'][0]) self.assertTrue('categories' in returned_json_data) self.assertTrue('yAxis' in returned_json_data) diff --git a/core/tests/unit/views/test_ofm_stadium_statistics_view.py b/core/tests/unit/views/test_ofm_stadium_statistics_view.py index 4f4befc..7f2d9dd 100644 --- a/core/tests/unit/views/test_ofm_stadium_statistics_view.py +++ b/core/tests/unit/views/test_ofm_stadium_statistics_view.py @@ -43,10 +43,10 @@ def test_user_can_see_his_latest_stadium_statistics_when_given_no_season(self): returned_json_data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEquals(len(returned_json_data), 1) + self.assertEqual(len(returned_json_data), 1) - self.assertEquals(returned_json_data[0]['visitors'], 168) - self.assertEquals(returned_json_data[0]['capacity'], 400) + self.assertEqual(returned_json_data[0]['visitors'], 168) + self.assertEqual(returned_json_data[0]['capacity'], 400) def test_user_can_only_see_his_stadium_statistics(self): user2 = OFMUser.objects.create_user(username='bob', password='bob') @@ -61,11 +61,11 @@ def test_user_can_only_see_his_stadium_statistics(self): returned_json_data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEquals(len(returned_json_data), 1) + self.assertEqual(len(returned_json_data), 1) - self.assertEquals(returned_json_data[0]['visitors'], 168) - self.assertEquals(returned_json_data[0]['capacity'], 400) - self.assertEquals(returned_json_data[0]['venue'], self.match.venue) + self.assertEqual(returned_json_data[0]['visitors'], 168) + self.assertEqual(returned_json_data[0]['capacity'], 400) + self.assertEqual(returned_json_data[0]['venue'], self.match.venue) def test_get_two_different_matches_with_same_harmonic_strength(self): match2 = MatchFactory.create(user=self.user, home_team_statistics__strength=30, guest_team_statistics__strength=150) @@ -79,14 +79,14 @@ def test_get_two_different_matches_with_same_harmonic_strength(self): response = self.client.get(reverse('core:ofm:stadium_statistics_overview_json'), options) returned_json_data = json.loads(response.content.decode('utf-8')) - self.assertEquals(len(returned_json_data), 2) + self.assertEqual(len(returned_json_data), 2) - self.assertEquals(returned_json_data[0]['home_strength'], 50) - self.assertEquals(returned_json_data[0]['guest_strength'], 50) - self.assertEquals(str(returned_json_data[0]['harmonic_strength'])[:2], '50') - self.assertEquals(returned_json_data[1]['home_strength'], 30) - self.assertEquals(returned_json_data[1]['guest_strength'], 150) - self.assertEquals(str(returned_json_data[1]['harmonic_strength'])[:2], '50') + self.assertEqual(returned_json_data[0]['home_strength'], 50) + self.assertEqual(returned_json_data[0]['guest_strength'], 50) + self.assertEqual(str(returned_json_data[0]['harmonic_strength'])[:2], '50') + self.assertEqual(returned_json_data[1]['home_strength'], 30) + self.assertEqual(returned_json_data[1]['guest_strength'], 150) + self.assertEqual(str(returned_json_data[1]['harmonic_strength'])[:2], '50') def test_user_can_narrow_statistics_with_strength_slider_by_cookie(self): cookies = self.client.cookies @@ -103,14 +103,14 @@ def test_user_can_narrow_statistics_with_strength_slider_by_cookie(self): returned_json_data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEquals(len(returned_json_data), 1) + self.assertEqual(len(returned_json_data), 1) - self.assertEquals(returned_json_data[0]['visitors'], 168) - self.assertEquals(returned_json_data[0]['capacity'], 400) - self.assertEquals(returned_json_data[0]['home_strength'], 50) - self.assertEquals(returned_json_data[0]['guest_strength'], 50) - self.assertEquals(str(returned_json_data[0]['harmonic_strength'])[:2], '50') - self.assertEquals(returned_json_data[0]['venue'], self.match.venue) + self.assertEqual(returned_json_data[0]['visitors'], 168) + self.assertEqual(returned_json_data[0]['capacity'], 400) + self.assertEqual(returned_json_data[0]['home_strength'], 50) + self.assertEqual(returned_json_data[0]['guest_strength'], 50) + self.assertEqual(str(returned_json_data[0]['harmonic_strength'])[:2], '50') + self.assertEqual(returned_json_data[0]['venue'], self.match.venue) def test_default_values_from_last_match_for_strength_slider(self): matchday = MatchdayFactory.create(number=2) @@ -155,4 +155,4 @@ def test_user_can_filter_for_stadium_configuration(self): returned_json_data = json.loads(response.content.decode('utf-8')) self.assertEqual(response.status_code, 200) - self.assertEquals(len(returned_json_data), 1) + self.assertEqual(len(returned_json_data), 1) diff --git a/core/tests/unit/views/test_parser_view.py b/core/tests/unit/views/test_parser_view.py index 5e667a2..bef7746 100644 --- a/core/tests/unit/views/test_parser_view.py +++ b/core/tests/unit/views/test_parser_view.py @@ -88,7 +88,7 @@ def test_match_parser_view(self, matchday_parser_mock, match_parser_mock, parse_ @patch('core.managers.parser_manager.ParserManager.parse_awp_boundaries') @patch('core.managers.parser_manager.ParserManager.parse_ofm_version') def test_parser_view(self, site_manager_mock, parse_matchday_mock, parse_players_mock, parse_player_statistics_mock, - parse_finances_mock, parse_all_matches_mock, parse_awp_mock, parse_version_mock): + parse_finances_mock, parse_all_matches_mock, parse_awp_mock, parse_version_mock): # noqa response = self.client.get(reverse('core:trigger_parsing')) self.assertEqual(response.status_code, 302) diff --git a/core/tests/unit/views/test_settings_view.py b/core/tests/unit/views/test_settings_view.py index 69819f8..e3468b3 100644 --- a/core/tests/unit/views/test_settings_view.py +++ b/core/tests/unit/views/test_settings_view.py @@ -92,5 +92,5 @@ def test_get_current_matchday(self): response = self.client.get(reverse('core:get_current_matchday')) self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) - self.assertEquals(returned_json_data['matchday_number'], 0) - self.assertEquals(returned_json_data['season_number'], 1) + self.assertEqual(returned_json_data['matchday_number'], 0) + self.assertEqual(returned_json_data['season_number'], 1) From 0e9b69f00bc58f29b05fb2d4df4919a963f7b653 Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Mon, 5 Dec 2016 17:26:53 +0100 Subject: [PATCH 10/71] forgot one deprecated test --- .../tests/unit/parser/test_finances_parser.py | 50 +++++++++---------- 1 file changed, 25 insertions(+), 25 deletions(-) diff --git a/core/tests/unit/parser/test_finances_parser.py b/core/tests/unit/parser/test_finances_parser.py index f0d3b24..2a37f09 100644 --- a/core/tests/unit/parser/test_finances_parser.py +++ b/core/tests/unit/parser/test_finances_parser.py @@ -19,28 +19,28 @@ def setUp(self): self.finances = self.parser.parse() def test_finances_parser(self): - self.assertEquals(type(self.finances), Finance) - - self.assertEquals('1633872', self.finances.balance) - - self.assertEquals('54450', self.finances.income_visitors_league) - self.assertEquals('0', self.finances.income_sponsoring) - self.assertEquals('0', self.finances.income_cup) - self.assertEquals('20749', self.finances.income_interests) - self.assertEquals('0', self.finances.income_loan) - self.assertEquals('0', self.finances.income_transfer) - self.assertEquals('0', self.finances.income_visitors_friendlies) - self.assertEquals('30000', self.finances.income_friendlies) - self.assertEquals('0', self.finances.income_funcup) - self.assertEquals('0', self.finances.income_betting) - - self.assertEquals('167945', self.finances.expenses_player_salaries) - self.assertEquals('432000', self.finances.expenses_stadium) - self.assertEquals('8280', self.finances.expenses_youth) - self.assertEquals('0', self.finances.expenses_interests) - self.assertEquals('0', self.finances.expenses_trainings) - self.assertEquals('0', self.finances.expenses_transfer) - self.assertEquals('0', self.finances.expenses_compensation) - self.assertEquals('0', self.finances.expenses_friendlies) - self.assertEquals('0', self.finances.expenses_funcup) - self.assertEquals('0', self.finances.expenses_betting) + self.assertEqual(type(self.finances), Finance) + + self.assertEqual('1633872', self.finances.balance) + + self.assertEqual('54450', self.finances.income_visitors_league) + self.assertEqual('0', self.finances.income_sponsoring) + self.assertEqual('0', self.finances.income_cup) + self.assertEqual('20749', self.finances.income_interests) + self.assertEqual('0', self.finances.income_loan) + self.assertEqual('0', self.finances.income_transfer) + self.assertEqual('0', self.finances.income_visitors_friendlies) + self.assertEqual('30000', self.finances.income_friendlies) + self.assertEqual('0', self.finances.income_funcup) + self.assertEqual('0', self.finances.income_betting) + + self.assertEqual('167945', self.finances.expenses_player_salaries) + self.assertEqual('432000', self.finances.expenses_stadium) + self.assertEqual('8280', self.finances.expenses_youth) + self.assertEqual('0', self.finances.expenses_interests) + self.assertEqual('0', self.finances.expenses_trainings) + self.assertEqual('0', self.finances.expenses_transfer) + self.assertEqual('0', self.finances.expenses_compensation) + self.assertEqual('0', self.finances.expenses_friendlies) + self.assertEqual('0', self.finances.expenses_funcup) + self.assertEqual('0', self.finances.expenses_betting) From caec038edfc5c2a1ef90140d2acfc9c81db44285 Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Mon, 5 Dec 2016 17:43:00 +0100 Subject: [PATCH 11/71] one unused variable less --- core/parsers/finances_parser.py | 2 +- core/parsers/match_parser.py | 2 +- core/parsers/matchday_parser.py | 4 ++-- core/parsers/player_statistics_parser.py | 2 +- core/parsers/players_parser.py | 8 ++++---- core/parsers/stadium_stand_statistics_parser.py | 4 ++-- core/parsers/stadium_statistics_parser.py | 6 +++--- core/parsers/won_by_default_match_row_parser.py | 2 +- core/tests/unit/parser/test_player_statistics_parser.py | 4 +--- 9 files changed, 16 insertions(+), 18 deletions(-) diff --git a/core/parsers/finances_parser.py b/core/parsers/finances_parser.py index d38e698..271be3a 100644 --- a/core/parsers/finances_parser.py +++ b/core/parsers/finances_parser.py @@ -51,7 +51,7 @@ def parse_html(self, soup): expenses_funcup = self._int_from_money(finance_values[12].find_all('td')[11].div.get_text()) expenses_betting = self._int_from_money(finance_values[13].find_all('td')[11].div.get_text()) - finances, success = Finance.objects.get_or_create( + finances, _ = Finance.objects.get_or_create( user=self.user, matchday=self.matchday, ) diff --git a/core/parsers/match_parser.py b/core/parsers/match_parser.py index a97e286..899c1f5 100644 --- a/core/parsers/match_parser.py +++ b/core/parsers/match_parser.py @@ -29,7 +29,7 @@ def parse_html(self, soup): # we assume to have parsed the season beforehand (via matchday) season = Matchday.objects.all()[0].season matchday_number = soup.find_all('tbody')[2].find_all('b')[0].get_text().split(',')[1].split('.')[0].strip() - matchday, success = Matchday.objects.get_or_create(season=season, number=matchday_number) + matchday, _ = Matchday.objects.get_or_create(season=season, number=matchday_number) venue = soup.find_all('em')[1].get_text() match_result = soup.find_all('table')[5].find_all('tr')[0].find_all('td')[3].div.font.get_text() diff --git a/core/parsers/matchday_parser.py b/core/parsers/matchday_parser.py index 2a1e5c6..07a93ec 100644 --- a/core/parsers/matchday_parser.py +++ b/core/parsers/matchday_parser.py @@ -16,11 +16,11 @@ def parse(self): matchday_number = int(soup.body.find_all('div')[1].div.find_all('p')[2].find_all('span')[0].get_text()) matchday_season_number = int(soup.body.find_all('div')[1].div.find_all('p')[2].find_all('span')[1].get_text()) - season, season_creation_success = Season.objects.get_or_create( + season, _ = Season.objects.get_or_create( number=matchday_season_number, ) - matchday, matchday_creation_success = Matchday.objects.get_or_create( + matchday, _ = Matchday.objects.get_or_create( number=matchday_number, season=season, ) diff --git a/core/parsers/player_statistics_parser.py b/core/parsers/player_statistics_parser.py index 960b2dc..8d4ecba 100644 --- a/core/parsers/player_statistics_parser.py +++ b/core/parsers/player_statistics_parser.py @@ -57,7 +57,7 @@ def parse_row(self, player_row): player = self._parse_player(player_stat_values) - parsed_player_stat, success = PlayerStatistics.objects.get_or_create( + parsed_player_stat, _ = PlayerStatistics.objects.get_or_create( matchday=self.matchday, player=player ) diff --git a/core/parsers/players_parser.py b/core/parsers/players_parser.py index 0fa4d0c..69469e3 100644 --- a/core/parsers/players_parser.py +++ b/core/parsers/players_parser.py @@ -36,15 +36,15 @@ def parse_row(self, player_row): name = player_values[6].a.get_text().replace('\n', '').replace('\t', '').strip(' ') position = player_values[5].find_all('span')[1].get_text() age = int(player_values[7].get_text()) - birth_season, success = Season.objects.get_or_create(number=self.matchday.season.number - age) + birth_season, _ = Season.objects.get_or_create(number=self.matchday.season.number - age) displayed_country = player_values[8].get_text().replace('\n', '').replace('\t', '').strip(' ') country_name = ''.join([i for i in displayed_country if not i.isdigit()]) country_choices = dict(Country._meta.get_field('country').choices) country_no = list(country_choices.keys())[list(country_choices.values()).index(country_name)] - nationality, success = Country.objects.get_or_create(country=country_no) + nationality, _ = Country.objects.get_or_create(country=country_no) - player, success = Player.objects.get_or_create(id=int(ofm_id), + player, _ = Player.objects.get_or_create(id=int(ofm_id), birth_season=birth_season, nationality=nationality, position=position) @@ -64,7 +64,7 @@ def _create_contract(self, player): if existing_contracts.count() > 0: contract = existing_contracts[0] else: - contract, success = Contract.objects.get_or_create( + contract, _ = Contract.objects.get_or_create( player=player, user=self.user, bought_on_matchday=self.matchday diff --git a/core/parsers/stadium_stand_statistics_parser.py b/core/parsers/stadium_stand_statistics_parser.py index c952510..40881db 100644 --- a/core/parsers/stadium_stand_statistics_parser.py +++ b/core/parsers/stadium_stand_statistics_parser.py @@ -48,12 +48,12 @@ def _parse_stand_statistics(self, stand_data): condition = stand_data.find_all('tr')[2].find_all('td')[0].find_all('span')[1].get_text().replace(',', '.').replace('%', '') ticket_price = stand_data.find_all('tr')[6].find_all('select')[0].find('option', selected=True).get('value') - stand_level, success = StandLevel.objects.get_or_create( + stand_level, _ = StandLevel.objects.get_or_create( capacity=capacity, has_roof=has_roof, has_seats=has_seats ) - stadium_stand_stat, success = StadiumStandStatistics.objects.get_or_create( + stadium_stand_stat, _ = StadiumStandStatistics.objects.get_or_create( stadium_statistics=self.match_stadium_stat, sector=sector, visitors=visitors, diff --git a/core/parsers/stadium_statistics_parser.py b/core/parsers/stadium_statistics_parser.py index 7f5b538..1f30aeb 100644 --- a/core/parsers/stadium_statistics_parser.py +++ b/core/parsers/stadium_statistics_parser.py @@ -64,14 +64,14 @@ def parse_html(self, soup): else: parking = self._create_stadium_level_item_from_row(parking_row) - stadium_level, success = StadiumLevel.objects.get_or_create( + stadium_level, _ = StadiumLevel.objects.get_or_create( light=light, screen=screen, security=security, parking=parking ) - match_stadium_stat, success = MatchStadiumStatistics.objects.get_or_create( + match_stadium_stat, _ = MatchStadiumStatistics.objects.get_or_create( match=self.match, level=stadium_level ) @@ -83,7 +83,7 @@ def _create_stadium_level_item_from_row(self, row): value = self.strip_euro_sign(row.find_all('td')[4].span.get_text().replace('.', '').strip()) daily_costs = self.strip_euro_sign(row.find_all('td')[5].span.get_text().replace('.', '').strip()) - stadium_level_item, success = StadiumLevelItem.objects.get_or_create( + stadium_level_item, _ = StadiumLevelItem.objects.get_or_create( current_level=level, value=value, daily_costs=daily_costs diff --git a/core/parsers/won_by_default_match_row_parser.py b/core/parsers/won_by_default_match_row_parser.py index f470dea..807c982 100644 --- a/core/parsers/won_by_default_match_row_parser.py +++ b/core/parsers/won_by_default_match_row_parser.py @@ -26,7 +26,7 @@ def parse_html(self, row): # we assume to have parsed the season beforehand (with the matchday) season = Matchday.objects.all()[0].season matchday_number = row.find_all('td')[0].get_text().replace('\n', '') - matchday, success = Matchday.objects.get_or_create(season=season, number=matchday_number) + matchday, _ = Matchday.objects.get_or_create(season=season, number=matchday_number) is_home_match = "black" in row.find_all('td')[1].a.get('class') diff --git a/core/tests/unit/parser/test_player_statistics_parser.py b/core/tests/unit/parser/test_player_statistics_parser.py index 1480c6f..2319cbc 100644 --- a/core/tests/unit/parser/test_player_statistics_parser.py +++ b/core/tests/unit/parser/test_player_statistics_parser.py @@ -18,9 +18,7 @@ def setUp(self): country_choices = dict(Country._meta.get_field('country').choices) country_no_greece = list(country_choices.keys())[list(country_choices.values()).index('Griechenland')] - nationality_greece, success = Country.objects.get_or_create(country=country_no_greece) - - self.assertTrue(success) + nationality_greece, _ = Country.objects.get_or_create(country=country_no_greece) self.player = Player.objects.create(id='159883060', position='TW', name='Chrístos Tsigas', birth_season=season, nationality=nationality_greece) self.player = Player.objects.create(id='160195494', position='LV', name='Irwin O\'Canny', birth_season=season, nationality=nationality_greece) From 62f9beb93b2ffa0df85b9dbdddc4b93fcad291ef Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Mon, 5 Dec 2016 17:52:36 +0100 Subject: [PATCH 12/71] use newer string replacing syntax --- core/parsers/matchday_parser.py | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/core/parsers/matchday_parser.py b/core/parsers/matchday_parser.py index 07a93ec..ab26556 100644 --- a/core/parsers/matchday_parser.py +++ b/core/parsers/matchday_parser.py @@ -1,8 +1,9 @@ +import logging + from bs4 import BeautifulSoup from core.models import Matchday, Season from core.parsers.base_parser import BaseParser -import logging logger = logging.getLogger(__name__) @@ -27,6 +28,6 @@ def parse(self): matchday.season.save() matchday.save() - logger.debug('===== Matchday parsed: %s ' % matchday) + logger.debug('===== Matchday parsed: {} '.format(matchday)) return matchday From 0ca40e0533df4a5f012b40151458555799e5e53c Mon Sep 17 00:00:00 2001 From: "sebastian.schreck" Date: Mon, 5 Dec 2016 19:14:08 +0100 Subject: [PATCH 13/71] fix some pylint errors --- core/ofm_views.py | 84 +++++++++++-------- core/parsers/player_statistics_parser.py | 2 +- core/parsers/stadium_statistics_parser.py | 12 ++- .../parser/test_player_statistics_parser.py | 24 +++++- core/tests/unit/parser/test_players_parser.py | 6 +- core/tests/unit/test_core_models.py | 9 +- .../views/test_checklist_settings_view.py | 70 +++++++++++++--- .../views/test_ofm_finances_charts_views.py | 18 +++- .../unit/views/test_ofm_finances_view.py | 38 +++++++-- .../tests/unit/views/test_ofm_matches_view.py | 16 +++- .../unit/views/test_ofm_player_detail_view.py | 34 ++++++-- .../views/test_ofm_player_statistics_view.py | 44 +++++++--- .../views/test_ofm_stadium_detail_view.py | 18 +++- .../test_ofm_stadium_stand_statistics_view.py | 18 +++- .../views/test_ofm_stadium_statistics_view.py | 19 ++++- core/tests/unit/views/test_settings_view.py | 8 +- 16 files changed, 320 insertions(+), 100 deletions(-) diff --git a/core/ofm_views.py b/core/ofm_views.py index ef14ad5..bdd9877 100644 --- a/core/ofm_views.py +++ b/core/ofm_views.py @@ -49,17 +49,18 @@ def get(self, request, *args, **kwargs): player_statistics_tuples = [] for player in players: - newer_player_statistics, older_player_statistics = self._get_statistics_from_player_and_matchday(player, - newer_matchday_season, - newer_matchday, - older_matchday_season, - older_matchday) + newer_player_statistics, older_player_statistics = self._get_statistics_from_player_and_matchday( + player, + newer_matchday_season, newer_matchday, + older_matchday_season, older_matchday + ) if newer_player_statistics and (older_player_statistics or not diff_mode_enabled): player_statistics_tuples.append((newer_player_statistics, older_player_statistics)) player_statistics_json = [ self._get_player_statistics_diff_in_json(newer_player_statistics, older_player_statistics) - for (newer_player_statistics, older_player_statistics) in player_statistics_tuples] + for (newer_player_statistics, older_player_statistics) in player_statistics_tuples + ] return self.render_json_response(player_statistics_json) @@ -67,20 +68,25 @@ def _get_statistics_from_player_and_matchday(self, player, newer_matchday_season, newer_matchday, older_matchday_season, older_matchday): - newer_player_statistics = PlayerStatistics.objects.filter(player=player, - matchday__season__number=newer_matchday_season, - matchday__number=newer_matchday) - older_player_statistics = PlayerStatistics.objects.filter(player=player, - matchday__season__number=older_matchday_season, - matchday__number=older_matchday) + newer_player_statistics = PlayerStatistics.objects.filter( + player=player, + matchday__season__number=newer_matchday_season, + matchday__number=newer_matchday + ) + older_player_statistics = PlayerStatistics.objects.filter( + player=player, + matchday__season__number=older_matchday_season, + matchday__number=older_matchday + ) newer_player_statistics = _validate_filtered_field(newer_player_statistics) older_player_statistics = _validate_filtered_field(older_player_statistics) if not newer_player_statistics: - newer_player_statistics = \ - PlayerStatistics.objects.filter(player=player, matchday__season__number=newer_matchday_season).order_by( - 'matchday')[0] + newer_player_statistics = PlayerStatistics.objects.filter( + player=player, + matchday__season__number=newer_matchday_season + ).order_by('matchday')[0] return newer_player_statistics, older_player_statistics @@ -117,8 +123,8 @@ def _get_player_statistics_diff_in_json(self, newer_player_statistics, older_pla statistic_diff['position'] = newer_player_statistics.player.position statistic_diff['age'] = newer_player_statistics.age statistic_diff['strength'] = strength - statistic_diff['name'] = '%s' % ( - newer_player_statistics.player.get_absolute_url(), newer_player_statistics.player.name) + statistic_diff['name'] = '%s' % (newer_player_statistics.player.get_absolute_url(), + newer_player_statistics.player.name) statistic_diff['ep'] = ep statistic_diff['tp'] = tp statistic_diff['awp'] = awp @@ -221,10 +227,16 @@ def get(self, request, *args, **kwargs): older_matchday_season = self.request.GET.get('older_matchday_season') older_matchday = self.request.GET.get('older_matchday') - newer_finances = Finance.objects.filter(user=request.user, matchday__season__number=newer_matchday_season, - matchday__number=newer_matchday) - older_finances = Finance.objects.filter(user=request.user, matchday__season__number=older_matchday_season, - matchday__number=older_matchday) + newer_finances = Finance.objects.filter( + user=request.user, + matchday__season__number=newer_matchday_season, + matchday__number=newer_matchday + ) + older_finances = Finance.objects.filter( + user=request.user, + matchday__season__number=older_matchday_season, + matchday__number=older_matchday + ) newer_finances = _validate_filtered_field(newer_finances) older_finances = _validate_filtered_field(older_finances) @@ -666,8 +678,8 @@ def get_context_data(self, **kwargs): slider_max = self.request.COOKIES['slider_max'] tolerance = self.request.COOKIES['tolerance'] elif Match.objects.count() > 0: - match = Match.objects.filter(user=self.request.user, is_home_match=True).order_by('matchday')[ - 0] # latest home match + # latest home match + match = Match.objects.filter(user=self.request.user, is_home_match=True).order_by('matchday')[0] slider_min = int(min(match.home_team_statistics.strength, match.guest_team_statistics.strength)) slider_max = int(max(match.home_team_statistics.strength, match.guest_team_statistics.strength)) else: @@ -694,8 +706,9 @@ class StadiumStatisticsAsJsonView(CsrfExemptMixin, JsonRequestResponseMixin, Vie def get(self, request, *args, **kwargs): harmonic_strength = 150 tolerance = 5 - if self.request.COOKIES.get('slider_min') and self.request.COOKIES.get( - 'slider_max') and self.request.COOKIES.get('tolerance'): + if self.request.COOKIES.get('slider_min') and \ + self.request.COOKIES.get('slider_max') and \ + self.request.COOKIES.get('tolerance'): slider_min = int(self.request.COOKIES['slider_min']) slider_max = int(self.request.COOKIES['slider_max']) tolerance = int(self.request.COOKIES['tolerance']) @@ -822,14 +835,17 @@ def get_context_data(self, **kwargs): current_season_number = Matchday.objects.all()[0].season.number sector = self.request.GET.get('sector', 'N') season_number = self.request.GET.get('season', current_season_number) - queryset = StadiumStandStatistics.objects.filter(stadium_statistics__match__user=self.request.user, - stadium_statistics__match__matchday__season__number=season_number, - sector=sector) + queryset = StadiumStandStatistics.objects.filter( + stadium_statistics__match__user=self.request.user, + stadium_statistics__match__matchday__season__number=season_number, + sector=sector + ) seasons = [] sectors = [] - statistics = StadiumStandStatistics.objects.filter(stadium_statistics__match__user=self.request.user).order_by( - 'stadium_statistics__match__matchday') + statistics = StadiumStandStatistics.objects.filter( + stadium_statistics__match__user=self.request.user + ).order_by('stadium_statistics__match__matchday') for stat in statistics: if stat.stadium_statistics.match.matchday.season not in seasons: seasons.append(stat.stadium_statistics.match.matchday.season) @@ -853,9 +869,11 @@ def get(self, request, *args, **kwargs): current_season_number = Matchday.objects.all()[0].season.number season_number = self.request.GET.get('season_number', default=current_season_number) sector = self.request.GET.get('sector', 'N') - statistics = StadiumStandStatistics.objects.filter(stadium_statistics__match__user=self.request.user, - stadium_statistics__match__matchday__season__number=season_number, - sector=sector) + statistics = StadiumStandStatistics.objects.filter( + stadium_statistics__match__user=self.request.user, + stadium_statistics__match__matchday__season__number=season_number, + sector=sector + ) chart_json = { "series": [{ diff --git a/core/parsers/player_statistics_parser.py b/core/parsers/player_statistics_parser.py index 8d4ecba..b03cf4a 100644 --- a/core/parsers/player_statistics_parser.py +++ b/core/parsers/player_statistics_parser.py @@ -96,7 +96,7 @@ def _create_contract(self, player): if existing_contracts.count() > 0: contract = existing_contracts[0] else: - contract, success = Contract.objects.get_or_create( + contract, _ = Contract.objects.get_or_create( player=player, user=self.user, bought_on_matchday=self.matchday diff --git a/core/parsers/stadium_statistics_parser.py b/core/parsers/stadium_statistics_parser.py index 1f30aeb..b8ee5de 100644 --- a/core/parsers/stadium_statistics_parser.py +++ b/core/parsers/stadium_statistics_parser.py @@ -39,10 +39,14 @@ def parse_html(self, soup): security_row = stadium_items[2] parking_row = stadium_items[3] - is_light_under_construction = light_row.find_all('td')[1].img is not None and 'underconst' in light_row.find_all('td')[1].img['src'] - is_screen_under_construction = screen_row.find_all('td')[1].img is not None and 'underconst' in screen_row.find_all('td')[1].img['src'] - is_security_under_construction = security_row.find_all('td')[1].img is not None and 'underconst' in security_row.find_all('td')[1].img['src'] - is_parking_under_construction = parking_row.find_all('td')[1].img is not None and 'underconst' in parking_row.find_all('td')[1].img['src'] + is_light_under_construction = \ + light_row.find_all('td')[1].img is not None and 'underconst' in light_row.find_all('td')[1].img['src'] + is_screen_under_construction = \ + screen_row.find_all('td')[1].img is not None and 'underconst' in screen_row.find_all('td')[1].img['src'] + is_security_under_construction = \ + security_row.find_all('td')[1].img is not None and 'underconst' in security_row.find_all('td')[1].img['src'] + is_parking_under_construction = \ + parking_row.find_all('td')[1].img is not None and 'underconst' in parking_row.find_all('td')[1].img['src'] if is_light_under_construction and last_stadium_level: light = last_stadium_level.light diff --git a/core/tests/unit/parser/test_player_statistics_parser.py b/core/tests/unit/parser/test_player_statistics_parser.py index 2319cbc..3365c3d 100644 --- a/core/tests/unit/parser/test_player_statistics_parser.py +++ b/core/tests/unit/parser/test_player_statistics_parser.py @@ -20,9 +20,27 @@ def setUp(self): country_no_greece = list(country_choices.keys())[list(country_choices.values()).index('Griechenland')] nationality_greece, _ = Country.objects.get_or_create(country=country_no_greece) - self.player = Player.objects.create(id='159883060', position='TW', name='Chrístos Tsigas', birth_season=season, nationality=nationality_greece) - self.player = Player.objects.create(id='160195494', position='LV', name='Irwin O\'Canny', birth_season=season, nationality=nationality_greece) - self.player = Player.objects.create(id='159341445', position='LMD', name='Jan Stemmler', birth_season=season, nationality=nationality_greece) + self.player = Player.objects.create( + id='159883060', + position='TW', + name='Chrístos Tsigas', + birth_season=season, + nationality=nationality_greece + ) + self.player = Player.objects.create( + id='160195494', + position='LV', + name='Irwin O\'Canny', + birth_season=season, + nationality=nationality_greece + ) + self.player = Player.objects.create( + id='159341445', + position='LMD', + name='Jan Stemmler', + birth_season=season, + nationality=nationality_greece + ) self.parser = PlayerStatisticsParser(testdata, user, self.matchday) self.player_stat_list = self.parser.parse() diff --git a/core/tests/unit/parser/test_players_parser.py b/core/tests/unit/parser/test_players_parser.py index 04c212d..411fd18 100644 --- a/core/tests/unit/parser/test_players_parser.py +++ b/core/tests/unit/parser/test_players_parser.py @@ -32,7 +32,11 @@ def test_parsed_player_contains_all_fields(self): self.assertEqual('Frankreich', str(self.first_player.nationality)) def test_parsed_player_has_contract_with_user(self): - self.assertEqual(1, len(Contract.objects.filter(player=self.first_player, user=self.user, sold_on_matchday=None))) + self.assertEqual(1, len(Contract.objects.filter( + player=self.first_player, + user=self.user, + sold_on_matchday=None + ))) def test_sold_player_gets_according_attribute(self): testdata = open(os.path.join(TESTDATA_PATH, 'players_one_player_sold.html'), encoding='utf8') diff --git a/core/tests/unit/test_core_models.py b/core/tests/unit/test_core_models.py index ef5dace..9e11d4e 100644 --- a/core/tests/unit/test_core_models.py +++ b/core/tests/unit/test_core_models.py @@ -48,8 +48,13 @@ def test_get_current_matchday_from_player_statistics(self): self.assertEqual(Matchday.get_current(), m3) def test_get_current_matchday_from_matches(self): - user2 = OFMUser.objects.create_user('second', 'second@ofmhelper.com', 'second', ofm_username="second", - ofm_password="second") + user2 = OFMUser.objects.create_user( + username='second', + email='second@ofmhelper.com', + password='second', + ofm_username="second", + ofm_password="second" + ) MatchdayFactory.create(number=1) m2 = MatchdayFactory.create(number=5) m3 = MatchdayFactory.create(number=7) diff --git a/core/tests/unit/views/test_checklist_settings_view.py b/core/tests/unit/views/test_checklist_settings_view.py index a84209a..e0460c9 100644 --- a/core/tests/unit/views/test_checklist_settings_view.py +++ b/core/tests/unit/views/test_checklist_settings_view.py @@ -11,10 +11,22 @@ class ChecklistSettingsTestCase(TestCase): def setUp(self): - self.user = OFMUser.objects.create_user('temporary', 'temporary@ofmhelper.com', 'temporary', ofm_username="tmp", ofm_password="temp") + self.user = OFMUser.objects.create_user( + username='temporary', + email='temporary@ofmhelper.com', + password='temporary', + ofm_username="tmp", + ofm_password="temp" + ) self.checklist = ChecklistFactory.create(user=self.user) self.checklist_item = ChecklistItemFactory.create(checklist=self.checklist, name='do more unit tests') - self.user2 = OFMUser.objects.create_user('second', 'second@ofmhelper.com', 'second', ofm_username="second", ofm_password="second") + self.user2 = OFMUser.objects.create_user( + username='second', + email='second@ofmhelper.com', + password='second', + ofm_username="second", + ofm_password="second" + ) checklist2 = ChecklistFactory.create(user=self.user2) ChecklistItemFactory.create(checklist=checklist2, name='do less unit tests') self.matchday = MatchdayFactory.create(number=6) @@ -211,11 +223,31 @@ def test_delete_checklist_item(self): def test_get_checklist_items_for_today(self): self.client.login(username='temporary', password='temporary') - c1 = ChecklistItemFactory.create(checklist=self.checklist, name='on 4th matchday', to_be_checked_on_matchdays='4') - c2 = ChecklistItemFactory.create(checklist=self.checklist, name='on every 4th matchday', to_be_checked_on_matchday_pattern=4) - c3 = ChecklistItemFactory.create(checklist=self.checklist, name='on every 3rd matchday', to_be_checked_on_matchday_pattern=3) - c4 = ChecklistItemFactory.create(checklist=self.checklist, name='if tomorrow home_match', to_be_checked_if_home_match_tomorrow=True) - c5 = ChecklistItemFactory.create(checklist=self.checklist, name='on 6th matchday', to_be_checked_on_matchdays='6,9') + c1 = ChecklistItemFactory.create( + checklist=self.checklist, + name='on 4th matchday', + to_be_checked_on_matchdays='4' + ) + c2 = ChecklistItemFactory.create( + checklist=self.checklist, + name='on every 4th matchday', + to_be_checked_on_matchday_pattern=4 + ) + c3 = ChecklistItemFactory.create( + checklist=self.checklist, + name='on every 3rd matchday', + to_be_checked_on_matchday_pattern=3 + ) + c4 = ChecklistItemFactory.create( + checklist=self.checklist, + name='if tomorrow home_match', + to_be_checked_if_home_match_tomorrow=True + ) + c5 = ChecklistItemFactory.create( + checklist=self.checklist, + name='on 6th matchday', + to_be_checked_on_matchdays='6,9' + ) response = self.client.get(reverse('core:settings_get_checklist_items_for_today')) @@ -234,10 +266,26 @@ def test_get_checklist_items_for_today_if_tomorrow_home_match(self): FinanceFactory.create(matchday=self.matchday, user=self.user) MatchFactory.create(matchday=matchday2, venue='', is_home_match=True, user=self.user) self.client.login(username='temporary', password='temporary') - c1 = ChecklistItemFactory.create(checklist=self.checklist, name='on 6th and 9th matchday', to_be_checked_on_matchdays='6,9') - c2 = ChecklistItemFactory.create(checklist=self.checklist, name='on every 2nd matchday', to_be_checked_on_matchday_pattern=2) - c3 = ChecklistItemFactory.create(checklist=self.checklist, name='on every 9th matchday', to_be_checked_on_matchday_pattern=9) - c4 = ChecklistItemFactory.create(checklist=self.checklist, name='if tomorrow home_match', to_be_checked_if_home_match_tomorrow=True) + c1 = ChecklistItemFactory.create( + checklist=self.checklist, + name='on 6th and 9th matchday', + to_be_checked_on_matchdays='6,9' + ) + c2 = ChecklistItemFactory.create( + checklist=self.checklist, + name='on every 2nd matchday', + to_be_checked_on_matchday_pattern=2 + ) + c3 = ChecklistItemFactory.create( + checklist=self.checklist, + name='on every 9th matchday', + to_be_checked_on_matchday_pattern=9 + ) + c4 = ChecklistItemFactory.create( + checklist=self.checklist, + name='if tomorrow home_match', + to_be_checked_if_home_match_tomorrow=True + ) response = self.client.get(reverse('core:settings_get_checklist_items_for_today')) diff --git a/core/tests/unit/views/test_ofm_finances_charts_views.py b/core/tests/unit/views/test_ofm_finances_charts_views.py index 892022f..793395a 100644 --- a/core/tests/unit/views/test_ofm_finances_charts_views.py +++ b/core/tests/unit/views/test_ofm_finances_charts_views.py @@ -11,11 +11,21 @@ class OFMFinancesViewTestCase(TestCase): def setUp(self): self.matchday = MatchdayFactory.create() self.next_matchday = MatchdayFactory.create(number=1) - self.user1 = OFMUser.objects.create_user(username='alice', email='alice@ofmhelper.com', password='alice', - ofm_username='alice', ofm_password='alice') + self.user1 = OFMUser.objects.create_user( + username='alice', + email='alice@ofmhelper.com', + password='alice', + ofm_username='alice', + ofm_password='alice' + ) self.finances = FinanceFactory.create(user=self.user1, matchday=self.matchday) - self.next_finances = FinanceFactory.create(user=self.user1, matchday=self.next_matchday, balance=2000, - income_visitors_league=200, expenses_player_salaries=200) + self.next_finances = FinanceFactory.create( + user=self.user1, + matchday=self.next_matchday, + balance=2000, + income_visitors_league=200, + expenses_player_salaries=200 + ) self.client.login(username='alice', password='alice') def test_finance_balance_chart_json(self): diff --git a/core/tests/unit/views/test_ofm_finances_view.py b/core/tests/unit/views/test_ofm_finances_view.py index ff4baac..a6e9801 100644 --- a/core/tests/unit/views/test_ofm_finances_view.py +++ b/core/tests/unit/views/test_ofm_finances_view.py @@ -11,11 +11,21 @@ class OFMFinancesViewTestCase(TestCase): def setUp(self): self.matchday = MatchdayFactory.create() self.next_matchday = MatchdayFactory.create(number=1) - self.user1 = OFMUser.objects.create_user(username='alice', email='alice@ofmhelper.com', password='alice', - ofm_username='alice', ofm_password='alice') + self.user1 = OFMUser.objects.create_user( + username='alice', + email='alice@ofmhelper.com', + password='alice', + ofm_username='alice', + ofm_password='alice' + ) self.finances = FinanceFactory.create(user=self.user1, matchday=self.matchday) - self.next_finances = FinanceFactory.create(user=self.user1, matchday=self.next_matchday, balance=2000, - income_visitors_league=200, expenses_player_salaries=200) + self.next_finances = FinanceFactory.create( + user=self.user1, + matchday=self.next_matchday, + balance=2000, + income_visitors_league=200, + expenses_player_salaries=200 + ) self.client.login(username='alice', password='alice') def test_user_can_see_his_finances(self): @@ -42,8 +52,15 @@ def test_user_can_see_his_latest_finances_when_given_no_matchday(self): def test_user_can_see_his_finances_diff_when_given_both_matchdays(self): third_matchday = MatchdayFactory.create(number=self.matchday.number + 2) - FinanceFactory.create(user=self.user1, matchday=third_matchday, balance=2500, income_visitors_league=250, - income_sponsoring=250, expenses_player_salaries=250, expenses_youth=100) + FinanceFactory.create( + user=self.user1, + matchday=third_matchday, + balance=2500, + income_visitors_league=250, + income_sponsoring=250, + expenses_player_salaries=250, + expenses_youth=100 + ) response = self.client.get(reverse('core:ofm:finances_json'), {'newer_matchday_season': third_matchday.season.number, @@ -64,8 +81,13 @@ def test_user_can_see_his_finances_diff_when_given_both_matchdays(self): def test_user_can_see_his_finances_diff_when_given_only_newer_matchday(self): third_matchday = MatchdayFactory.create(number=self.matchday.number + 2) - FinanceFactory.create(user=self.user1, matchday=third_matchday, balance=2500, income_visitors_league=250, - expenses_player_salaries=250) + FinanceFactory.create( + user=self.user1, + matchday=third_matchday, + balance=2500, + income_visitors_league=250, + expenses_player_salaries=250 + ) response = self.client.get(reverse('core:ofm:finances_json'), {'newer_matchday_season': third_matchday.season.number, diff --git a/core/tests/unit/views/test_ofm_matches_view.py b/core/tests/unit/views/test_ofm_matches_view.py index 70b3249..0d32171 100644 --- a/core/tests/unit/views/test_ofm_matches_view.py +++ b/core/tests/unit/views/test_ofm_matches_view.py @@ -11,8 +11,20 @@ class OFMMatchesViewTestCase(TestCase): def setUp(self): self.matchday = MatchdayFactory.create() self.second_matchday = MatchdayFactory.create(number=1) - self.user1 = OFMUser.objects.create_user(username='alice', email='alice@ofmhelper.com', password='alice', ofm_username='alice', ofm_password='alice') - self.user2 = OFMUser.objects.create_user('bob', 'bob@ofmhelper.com', 'bob', ofm_username='bob', ofm_password='bob') + self.user1 = OFMUser.objects.create_user( + username='alice', + email='alice@ofmhelper.com', + password='alice', + ofm_username='alice', + ofm_password='alice' + ) + self.user2 = OFMUser.objects.create_user( + username='bob', + email='bob@ofmhelper.com', + password='bob', + ofm_username='bob', + ofm_password='bob' + ) MatchFactory.create(user=self.user1) self.client.login(username='alice', password='alice') diff --git a/core/tests/unit/views/test_ofm_player_detail_view.py b/core/tests/unit/views/test_ofm_player_detail_view.py index 526738d..22e2c27 100644 --- a/core/tests/unit/views/test_ofm_player_detail_view.py +++ b/core/tests/unit/views/test_ofm_player_detail_view.py @@ -12,12 +12,26 @@ class OFMPlayerDetailViewTestCase(TestCase): def setUp(self): self.player = PlayerFactory.create() self.matchday = MatchdayFactory.create() - self.user1 = OFMUser.objects.create_user('alice', 'alice@ofmhelper.com', 'alice', ofm_username='alice', - ofm_password='alice') - self.user2 = OFMUser.objects.create_user('bob', 'bob@ofmhelper.com', 'bob', ofm_username='bob', - ofm_password='bob') - Contract.objects.create(user=self.user1, player=self.player, bought_on_matchday=self.matchday, - sold_on_matchday=None) + self.user1 = OFMUser.objects.create_user( + username='alice', + email='alice@ofmhelper.com', + password='alice', + ofm_username='alice', + ofm_password='alice' + ) + self.user2 = OFMUser.objects.create_user( + username='bob', + email='bob@ofmhelper.com', + password='bob', + ofm_username='bob', + ofm_password='bob' + ) + Contract.objects.create( + user=self.user1, + player=self.player, + bought_on_matchday=self.matchday, + sold_on_matchday=None + ) self.client.login(username='alice', password='alice') def test_user_can_see_his_players(self): @@ -77,8 +91,12 @@ def test_player_chart_shows_awp_boundaries_which_are_only_greater_than_my_streng def test_player_chart_shows_reached_but_not_promoted_awp_boundary(self): PlayerStatisticsFactory.create(player=self.player, matchday=self.matchday, strength=2, awp=2800) - PlayerStatisticsFactory.create(player=self.player, matchday=MatchdayFactory.create(number=1), strength=2, - awp=3500) + PlayerStatisticsFactory.create( + player=self.player, + matchday=MatchdayFactory.create(number=1), + strength=2, + awp=3500 + ) awp_boundaries = AwpBoundaries.get_or_create_from_matchday(self.matchday) awp_boundaries[2] = 2000 diff --git a/core/tests/unit/views/test_ofm_player_statistics_view.py b/core/tests/unit/views/test_ofm_player_statistics_view.py index ad96188..03ea725 100644 --- a/core/tests/unit/views/test_ofm_player_statistics_view.py +++ b/core/tests/unit/views/test_ofm_player_statistics_view.py @@ -13,14 +13,29 @@ def setUp(self): self.player = PlayerFactory.create() self.matchday = MatchdayFactory.create() self.second_matchday = MatchdayFactory.create(number=1) - self.user1 = OFMUser.objects.create_user(username='alice', email='alice@ofmhelper.com', password='alice', - ofm_username='alice', ofm_password='alice') - Contract.objects.create(user=self.user1, player=self.player, bought_on_matchday=self.matchday, - sold_on_matchday=None) + self.user1 = OFMUser.objects.create_user( + username='alice', + email='alice@ofmhelper.com', + password='alice', + ofm_username='alice', + ofm_password='alice' + ) + Contract.objects.create( + user=self.user1, + player=self.player, + bought_on_matchday=self.matchday, + sold_on_matchday=None + ) self.client.login(username='alice', password='alice') PlayerStatisticsFactory.create(player=self.player, matchday=self.matchday) - PlayerStatisticsFactory.create(player=self.player, matchday=self.second_matchday, ep=3, tp=6, awp=4, - freshness=5) + PlayerStatisticsFactory.create( + player=self.player, + matchday=self.second_matchday, + ep=3, + tp=6, + awp=4, + freshness=5 + ) def test_user_can_see_table(self): response = self.client.get(reverse('core:ofm:player_statistics')) @@ -111,8 +126,12 @@ def test_user_can_see_players_diff_to_next_awp_boundary_given_matchdays(self): def test_player_leaves_team_shows_only_older_player_data(self): player2 = PlayerFactory.create(name="Tricia McMillan") - Contract.objects.create(user=self.user1, player=player2, bought_on_matchday=self.matchday, - sold_on_matchday=self.matchday) + Contract.objects.create( + user=self.user1, + player=player2, + bought_on_matchday=self.matchday, + sold_on_matchday=self.matchday + ) PlayerStatisticsFactory.create(player=player2, matchday=self.matchday, ep=3, tp=6, awp=4, freshness=5) response = self.client.get(reverse('core:ofm:player_statistics_json'), @@ -133,9 +152,12 @@ def test_player_leaves_team_shows_only_older_player_data(self): def test_player_joins_team_shows_only_older_player_data(self): player2 = PlayerFactory.create(name="Tricia McMillan") - Contract.objects.create(user=self.user1, player=player2, bought_on_matchday=self.matchday, - sold_on_matchday=None) - + Contract.objects.create( + user=self.user1, + player=player2, + bought_on_matchday=self.matchday, + sold_on_matchday=None + ) PlayerStatisticsFactory.create(player=player2, matchday=self.second_matchday, ep=3, tp=6, awp=4, freshness=5) response = self.client.get(reverse('core:ofm:player_statistics_json'), diff --git a/core/tests/unit/views/test_ofm_stadium_detail_view.py b/core/tests/unit/views/test_ofm_stadium_detail_view.py index c5164bb..0f09069 100644 --- a/core/tests/unit/views/test_ofm_stadium_detail_view.py +++ b/core/tests/unit/views/test_ofm_stadium_detail_view.py @@ -9,10 +9,20 @@ class OFMStadiumDetailsViewTestCase(TestCase): def setUp(self): self.matchday = MatchdayFactory.create() self.second_matchday = MatchdayFactory.create(number=1) - self.user1 = OFMUser.objects.create_user(username='alice', email='alice@ofmhelper.com', password='alice', - ofm_username='alice', ofm_password='alice') - self.user2 = OFMUser.objects.create_user('bob', 'bob@ofmhelper.com', 'bob', ofm_username='bob', - ofm_password='bob') + self.user1 = OFMUser.objects.create_user( + username='alice', + email='alice@ofmhelper.com', + password='alice', + ofm_username='alice', + ofm_password='alice' + ) + self.user2 = OFMUser.objects.create_user( + username='bob', + email='bob@ofmhelper.com', + password='bob', + ofm_username='bob', + ofm_password='bob' + ) self.match = MatchFactory.create(user=self.user1) self.stadium_stat = MatchStadiumStatisticsFactory.create(match=self.match) self.north_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='N') diff --git a/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py b/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py index 5a08a86..ccd70bc 100644 --- a/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py +++ b/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py @@ -11,10 +11,20 @@ class OFMStadiumStandStatisticsViewTestCase(TestCase): def setUp(self): self.matchday = MatchdayFactory.create() - self.user1 = OFMUser.objects.create_user(username='alice', email='alice@ofmhelper.com', password='alice', - ofm_username='alice', ofm_password='alice') - self.user2 = OFMUser.objects.create_user('bob', 'bob@ofmhelper.com', 'bob', ofm_username='bob', - ofm_password='bob') + self.user1 = OFMUser.objects.create_user( + username='alice', + email='alice@ofmhelper.com', + password='alice', + ofm_username='alice', + ofm_password='alice' + ) + self.user2 = OFMUser.objects.create_user( + username='bob', + email='bob@ofmhelper.com', + password='bob', + ofm_username='bob', + ofm_password='bob' + ) self.match = MatchFactory.create(user=self.user1) self.stadium_stat = MatchStadiumStatisticsFactory.create(match=self.match) self.north_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='N') diff --git a/core/tests/unit/views/test_ofm_stadium_statistics_view.py b/core/tests/unit/views/test_ofm_stadium_statistics_view.py index 7f2d9dd..2ee1df2 100644 --- a/core/tests/unit/views/test_ofm_stadium_statistics_view.py +++ b/core/tests/unit/views/test_ofm_stadium_statistics_view.py @@ -33,7 +33,11 @@ def test_user_can_see_table(self): self.assertTrue('stadium_configurations' in response.context_data) def test_user_can_see_his_latest_stadium_statistics_when_given_no_season(self): - match2 = MatchFactory.create(user=self.user, home_team_statistics__strength=150, guest_team_statistics__strength=150) + match2 = MatchFactory.create( + user=self.user, + home_team_statistics__strength=150, + guest_team_statistics__strength=150 + ) stadium_stat = MatchStadiumStatisticsFactory.create(match=match2) StadiumStandStatisticsFactory.create(stadium_statistics=stadium_stat, sector='N') StadiumStandStatisticsFactory.create(stadium_statistics=stadium_stat, sector='S') @@ -68,7 +72,11 @@ def test_user_can_only_see_his_stadium_statistics(self): self.assertEqual(returned_json_data[0]['venue'], self.match.venue) def test_get_two_different_matches_with_same_harmonic_strength(self): - match2 = MatchFactory.create(user=self.user, home_team_statistics__strength=30, guest_team_statistics__strength=150) + match2 = MatchFactory.create( + user=self.user, + home_team_statistics__strength=30, + guest_team_statistics__strength=150 + ) MatchStadiumStatisticsFactory.create(match=match2) options = { @@ -114,7 +122,12 @@ def test_user_can_narrow_statistics_with_strength_slider_by_cookie(self): def test_default_values_from_last_match_for_strength_slider(self): matchday = MatchdayFactory.create(number=2) - match2 = MatchFactory.create(user=self.user, home_team_statistics__strength=30, guest_team_statistics__strength=150, matchday=matchday) + match2 = MatchFactory.create( + user=self.user, + home_team_statistics__strength=30, + guest_team_statistics__strength=150, + matchday=matchday + ) MatchStadiumStatisticsFactory.create(match=match2) response = self.client.get(reverse('core:ofm:stadium_statistics_overview')) diff --git a/core/tests/unit/views/test_settings_view.py b/core/tests/unit/views/test_settings_view.py index e3468b3..7d8a1b7 100644 --- a/core/tests/unit/views/test_settings_view.py +++ b/core/tests/unit/views/test_settings_view.py @@ -9,7 +9,13 @@ class SettingsTestCase(TestCase): def setUp(self): - self.user = OFMUser.objects.create_user('temporary', 'temporary@ofmhelper.com', 'temporary', ofm_username="tmp", ofm_password="temp") + self.user = OFMUser.objects.create_user( + username='temporary', + email='temporary@ofmhelper.com', + password='temporary', + ofm_username="tmp", + ofm_password="temp" + ) def test_view_account_settings_when_logged_in(self): self.client.login(username='temporary', password='temporary') From 66eeeea7830cdc412771b710c0b5f86098f8eecf Mon Sep 17 00:00:00 2001 From: "sebastian.schreck" Date: Tue, 6 Dec 2016 20:01:19 +0100 Subject: [PATCH 14/71] refactored constants to pass pylint --- core/managers/parser_manager.py | 14 +-- core/models.py | 6 +- core/web/ofm_page_constants.py | 178 ++++++++++++++------------------ 3 files changed, 86 insertions(+), 112 deletions(-) diff --git a/core/managers/parser_manager.py b/core/managers/parser_manager.py index 17a7f39..682a7df 100644 --- a/core/managers/parser_manager.py +++ b/core/managers/parser_manager.py @@ -34,7 +34,7 @@ def reset_parsing_flags(self): self.players_already_parsed = False def parse_ofm_version(self, site_manager): - site_manager.jump_to_frame(Constants.GITHUB.LATEST_RELEASE) + site_manager.jump_to_frame(Constants.GitHub.LATEST_RELEASE) version_parser = OfmHelperVersionParser(site_manager.browser.page_source) return version_parser.parse() @@ -46,14 +46,14 @@ def parse_matchday(self, request, site_manager): def parse_players(self, request, site_manager): if not self.parsed_matchday: self.parsed_matchday = self.parse_matchday(request, site_manager) - site_manager.jump_to_frame(Constants.TEAM.PLAYERS) + site_manager.jump_to_frame(Constants.Team.PLAYERS) players_parser = PlayersParser(site_manager.browser.page_source, request.user, self.parsed_matchday) return players_parser.parse() def parse_player_statistics(self, request, site_manager): if not self.players_already_parsed: self.parse_players(request, site_manager) - site_manager.jump_to_frame(Constants.TEAM.PLAYER_STATISTICS) + site_manager.jump_to_frame(Constants.Team.PLAYER_STATISTICS) player_stat_parser = PlayerStatisticsParser(site_manager.browser.page_source, request.user, self.parsed_matchday) return player_stat_parser.parse() @@ -69,14 +69,14 @@ def parse_awp_boundaries(self, request, site_manager): def parse_finances(self, request, site_manager): if not self.parsed_matchday: self.parsed_matchday = self.parse_matchday(request, site_manager) - site_manager.jump_to_frame(Constants.FINANCES.OVERVIEW) + site_manager.jump_to_frame(Constants.Finances.OVERVIEW) finances_parser = FinancesParser(site_manager.browser.page_source, request.user, self.parsed_matchday) return finances_parser.parse() def parse_all_matches(self, request, site_manager): if not self.parsed_matchday: self.parsed_matchday = self.parse_matchday(request, site_manager) - site_manager.jump_to_frame(Constants.LEAGUE.MATCH_SCHEDULE) + site_manager.jump_to_frame(Constants.League.MATCH_SCHEDULE) soup = BeautifulSoup(site_manager.browser.page_source, "html.parser") rows = soup.find(id='table_head').find_all('tr') @@ -111,10 +111,10 @@ def _parse_single_match(self, request, site_manager, row): return match_parser.parse() def _parse_stadium_statistics(self, request, site_manager, match): - site_manager.jump_to_frame(Constants.STADIUM.ENVIRONMENT) + site_manager.jump_to_frame(Constants.Stadium.ENVIRONMENT) stadium_statistics_parser = StadiumStatisticsParser(site_manager.browser.page_source, request.user, match) stadium_statistics_parser.parse() - site_manager.jump_to_frame(Constants.STADIUM.OVERVIEW) + site_manager.jump_to_frame(Constants.Stadium.OVERVIEW) stadium_stand_stat_parser = StadiumStandStatisticsParser(site_manager.browser.page_source, request.user, match) stadium_stand_stat_parser.parse() diff --git a/core/models.py b/core/models.py index b03b6db..0ad4664 100644 --- a/core/models.py +++ b/core/models.py @@ -781,11 +781,11 @@ def get_from_matchday(matchday): @staticmethod def _name_from_matchday(matchday): - if Constants.QUARTERS.FOURTH_QUARTER_LEVELP_UP_DAY <= matchday.number < Constants.QUARTERS.FIRST_QUARTER_LEVELP_UP_DAY: + if Constants.Quarters.FOURTH_QUARTER_LEVELP_UP_DAY <= matchday.number < Constants.Quarters.FIRST_QUARTER_LEVELP_UP_DAY: return 'awp_boundaries_' + str(matchday.season.number) + '_0' - elif Constants.QUARTERS.FIRST_QUARTER_LEVELP_UP_DAY <= matchday.number < Constants.QUARTERS.SECOND_QUARTER_LEVELP_UP_DAY: + elif Constants.Quarters.FIRST_QUARTER_LEVELP_UP_DAY <= matchday.number < Constants.Quarters.SECOND_QUARTER_LEVELP_UP_DAY: return 'awp_boundaries_' + str(matchday.season.number) + '_1' - elif Constants.QUARTERS.SECOND_QUARTER_LEVELP_UP_DAY <= matchday.number < Constants.QUARTERS.THIRD_QUARTER_LEVELP_UP_DAY: + elif Constants.Quarters.SECOND_QUARTER_LEVELP_UP_DAY <= matchday.number < Constants.Quarters.THIRD_QUARTER_LEVELP_UP_DAY: return 'awp_boundaries_' + str(matchday.season.number) + '_2' else: return 'awp_boundaries_' + str(matchday.season.number) + '_3' diff --git a/core/web/ofm_page_constants.py b/core/web/ofm_page_constants.py index e6d65f7..3827af0 100644 --- a/core/web/ofm_page_constants.py +++ b/core/web/ofm_page_constants.py @@ -4,129 +4,103 @@ class Constants: AWP_BOUNDARIES = 'http://www.ofm-forum.de/showthread.php?91605-aktuelle-Aufwertungsgrenzen/page9999' class Office: - pass - OFFICE = Office() - OFFICE.OFFICE = 'http://www.onlinefussballmanager.de/office/buero.php' - OFFICE.TEAM_INFO = 'http://www.onlinefussballmanager.de/league/teaminfo.php' - OFFICE.INGAME_EMAIL = 'http://www.onlinefussballmanager.de/user/ingamemail/index.php' - OFFICE.NOTES = 'http://www.onlinefussballmanager.de/user/ingamemail/index.php?page=notizen' - OFFICE.BETTING = 'http://www.onlinefussballmanager.de/office/wetten.php' - OFFICE.HISTORY = 'http://www.onlinefussballmanager.de/office/history.php' - OFFICE.OFM_HISTORY = 'http://www.onlinefussballmanager.de/office/ofm_history.php' - OFFICE.PROFILE = 'http://www.onlinefussballmanager.de/user/profil.php' + OFFICE = 'http://www.onlinefussballmanager.de/office/buero.php' + TEAM_INFO = 'http://www.onlinefussballmanager.de/league/teaminfo.php' + INGAME_EMAIL = 'http://www.onlinefussballmanager.de/user/ingamemail/index.php' + NOTES = 'http://www.onlinefussballmanager.de/user/ingamemail/index.php?page=notizen' + BETTING = 'http://www.onlinefussballmanager.de/office/wetten.php' + HISTORY = 'http://www.onlinefussballmanager.de/office/history.php' + OFM_HISTORY = 'http://www.onlinefussballmanager.de/office/ofm_history.php' + PROFILE = 'http://www.onlinefussballmanager.de/user/profil.php' class Team: - pass - TEAM = Team() - TEAM.PLAYERS = 'http://www.onlinefussballmanager.de/team/players.php' - TEAM.LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=liga' - TEAM.FRIENDLY_LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=friendly' - TEAM.CUP_LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=pokal' - TEAM.FUNCUP_LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=funcup' - TEAM.WORLD_CUP_LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=world_cup' - TEAM.TRAINING = 'http://www.onlinefussballmanager.de/team/training_2011.php' - TEAM.PLAYER_STATISTICS = 'http://www.onlinefussballmanager.de/team/players-statistics.php' - TEAM.YOUTH = 'http://www.onlinefussballmanager.de/team/youth.php' + PLAYERS = 'http://www.onlinefussballmanager.de/team/players.php' + LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=liga' + FRIENDLY_LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=friendly' + CUP_LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=pokal' + FUNCUP_LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=funcup' + WORLD_CUP_LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=world_cup' + TRAINING = 'http://www.onlinefussballmanager.de/team/training_2011.php' + PLAYER_STATISTICS = 'http://www.onlinefussballmanager.de/team/players-statistics.php' + YOUTH = 'http://www.onlinefussballmanager.de/team/youth.php' class Transfer: - pass - TRANSFER = Transfer() - TRANSFER.OFFERS = 'http://www.onlinefussballmanager.de/transfer/angebote.php' - TRANSFER.AMATEURS = 'http://www.onlinefussballmanager.de/transfer/amas.php' - TRANSFER.TRANSFER_MARKET = 'http://www.onlinefussballmanager.de/transfer/transfermarkt.php' - TRANSFER.PLAYERSWITCH = 'http://www.onlinefussballmanager.de/transfer/spielerwechsel.php' - TRANSFER.BIDDING = 'http://www.onlinefussballmanager.de/transfer/transfer_gebote.php' - TRANSFER.AWP_CALCULATOR = 'http://www.onlinefussballmanager.de/010_transfer/awp_rechner_noplus.php' - TRANSFER.MARKET_VALUES = 'http://www.onlinefussballmanager.de/transfer/marketvalues.php' + OFFERS = 'http://www.onlinefussballmanager.de/transfer/angebote.php' + AMATEURS = 'http://www.onlinefussballmanager.de/transfer/amas.php' + TRANSFER_MARKET = 'http://www.onlinefussballmanager.de/transfer/transfermarkt.php' + PLAYERSWITCH = 'http://www.onlinefussballmanager.de/transfer/spielerwechsel.php' + BIDDING = 'http://www.onlinefussballmanager.de/transfer/transfer_gebote.php' + AWP_CALCULATOR = 'http://www.onlinefussballmanager.de/010_transfer/awp_rechner_noplus.php' + MARKET_VALUES = 'http://www.onlinefussballmanager.de/transfer/marketvalues.php' class Stadium: - pass - STADIUM = Stadium() - STADIUM.OVERVIEW = 'http://www.onlinefussballmanager.de/stadium/stadium.php' - STADIUM.SPECTATORS = 'http://www.onlinefussballmanager.de/stadium/zuschauer.php' - STADIUM.ENVIRONMENT = 'http://www.onlinefussballmanager.de/stadium/stadium-environment.php' + OVERVIEW = 'http://www.onlinefussballmanager.de/stadium/stadium.php' + SPECTATORS = 'http://www.onlinefussballmanager.de/stadium/zuschauer.php' + ENVIRONMENT = 'http://www.onlinefussballmanager.de/stadium/stadium-environment.php' class Finances: - pass - FINANCES = Finances() - FINANCES.OVERVIEW = 'http://www.onlinefussballmanager.de/finances/finanzen.php' - FINANCES.BANK = 'http://www.onlinefussballmanager.de/finances/bank.php' - FINANCES.SPONSOR = 'http://www.onlinefussballmanager.de/finances/spon_waehlen.php' + OVERVIEW = 'http://www.onlinefussballmanager.de/finances/finanzen.php' + BANK = 'http://www.onlinefussballmanager.de/finances/bank.php' + SPONSOR = 'http://www.onlinefussballmanager.de/finances/spon_waehlen.php' class League: - pass - LEAGUE = League() - LEAGUE.MATCHDAY_TABLE = 'http://www.onlinefussballmanager.de/league/spieltag_tabelle_2.php' - LEAGUE.LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=liga' - LEAGUE.TOPSTARS = 'http://www.onlinefussballmanager.de/league/bestespieler.php' - LEAGUE.GOAL_SCORERS = 'http://www.onlinefussballmanager.de/league/torschuetzen.php' - LEAGUE.TACKLINGS = 'http://www.onlinefussballmanager.de/league/bestezwk.php' - LEAGUE.BAN_OR_INJURY = 'http://www.onlinefussballmanager.de/league/sperrenstatistik.php' - LEAGUE.FAIRPLAY = 'http://www.onlinefussballmanager.de/league/fairplay.php' - LEAGUE.STADIUMS = 'http://www.onlinefussballmanager.de/league/ligastadien.php' - LEAGUE.TEAMS = 'http://www.onlinefussballmanager.de/league/teamstatistik3.php' - LEAGUE.MATCH_SCHEDULE = 'http://www.onlinefussballmanager.de/league/teaminfo.php' - LEAGUE.SEASON_PATHWAY = 'http://www.onlinefussballmanager.de/league/saisonverlauf.php' + MATCHDAY_TABLE = 'http://www.onlinefussballmanager.de/league/spieltag_tabelle_2.php' + LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=liga' + TOPSTARS = 'http://www.onlinefussballmanager.de/league/bestespieler.php' + GOAL_SCORERS = 'http://www.onlinefussballmanager.de/league/torschuetzen.php' + TACKLINGS = 'http://www.onlinefussballmanager.de/league/bestezwk.php' + BAN_OR_INJURY = 'http://www.onlinefussballmanager.de/league/sperrenstatistik.php' + FAIRPLAY = 'http://www.onlinefussballmanager.de/league/fairplay.php' + STADIUMS = 'http://www.onlinefussballmanager.de/league/ligastadien.php' + TEAMS = 'http://www.onlinefussballmanager.de/league/teamstatistik3.php' + MATCH_SCHEDULE = 'http://www.onlinefussballmanager.de/league/teaminfo.php' + SEASON_PATHWAY = 'http://www.onlinefussballmanager.de/league/saisonverlauf.php' class OfmCup: - pass - OFM_CUP = OfmCup() - OFM_CUP.MATCH_SCHEDULE = 'http://www.onlinefussballmanager.de/ofm_cup/pokal2.php' - OFM_CUP.LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=pokal' - OFM_CUP.SCORERS = 'http://www.onlinefussballmanager.de/ofm_cup/poktorschuetzen.php' - OFM_CUP.SUSPENDED_PLAYERS = 'http://www.onlinefussballmanager.de/ofm_cup/poksperren.php' - OFM_CUP.HISTORY = 'http://www.onlinefussballmanager.de/ofm_cup/pokhistory.php' - OFM_CUP.RULES = 'http://www.onlinefussballmanager.de/ofm_cup/pokregeln2.php' + MATCH_SCHEDULE = 'http://www.onlinefussballmanager.de/ofm_cup/pokal2.php' + LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=pokal' + SCORERS = 'http://www.onlinefussballmanager.de/ofm_cup/poktorschuetzen.php' + SUSPENDED_PLAYERS = 'http://www.onlinefussballmanager.de/ofm_cup/poksperren.php' + HISTORY = 'http://www.onlinefussballmanager.de/ofm_cup/pokhistory.php' + RULES = 'http://www.onlinefussballmanager.de/ofm_cup/pokregeln2.php' class WorldCup: - pass - WORLD_CUP = WorldCup() - WORLD_CUP.MATCH_SCHEDULE = 'http://www.onlinefussballmanager.de/world_cup/worldcup.php' - WORLD_CUP.LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=world_cup' - WORLD_CUP.SCORERS = 'http://www.onlinefussballmanager.de/world_cup/worldcup-torschuetzen.php' - WORLD_CUP.SUSPENDED_PLAYERS = 'http://www.onlinefussballmanager.de/world_cup/worldcup-sperren.php' - WORLD_CUP.HISTORY = 'http://www.onlinefussballmanager.de/world_cup/worldcup-history.php' - WORLD_CUP.RULES = 'http://www.onlinefussballmanager.de/world_cup/worldcup-regeln.php' + MATCH_SCHEDULE = 'http://www.onlinefussballmanager.de/world_cup/worldcup.php' + LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=world_cup' + SCORERS = 'http://www.onlinefussballmanager.de/world_cup/worldcup-torschuetzen.php' + SUSPENDED_PLAYERS = 'http://www.onlinefussballmanager.de/world_cup/worldcup-sperren.php' + HISTORY = 'http://www.onlinefussballmanager.de/world_cup/worldcup-history.php' + RULES = 'http://www.onlinefussballmanager.de/world_cup/worldcup-regeln.php' class FunCup: - pass - FUN_CUP = FunCup() - FUN_CUP.MY_FUN_CUPS = 'http://www.onlinefussballmanager.de/funcups/funcup_meine.php' - FUN_CUP.SEARCH = 'http://www.onlinefussballmanager.de/funcups/funcup_uebersicht.php' - FUN_CUP.ORGANIZE = 'http://www.onlinefussballmanager.de/funcups/orga/funcup_organisieren.php?neu=true' - FUN_CUP.LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=funcup' - FUN_CUP.INSTRUCTIONS = 'http://www.onlinefussballmanager.de/funcups/funcup_anleitung.php' + MY_FUN_CUPS = 'http://www.onlinefussballmanager.de/funcups/funcup_meine.php' + SEARCH = 'http://www.onlinefussballmanager.de/funcups/funcup_uebersicht.php' + ORGANIZE = 'http://www.onlinefussballmanager.de/funcups/orga/funcup_organisieren.php?neu=true' + LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=funcup' + INSTRUCTIONS = 'http://www.onlinefussballmanager.de/funcups/funcup_anleitung.php' class Friendly: - pass - FRIENDLY = Friendly() - FRIENDLY.ORGANIZED = 'http://www.onlinefussballmanager.de/friendlies/organisierte_fr_2.php' - FRIENDLY.OFFER = 'http://www.onlinefussballmanager.de/friendlies/anbieten_fr.php' - FRIENDLY.ACCEPT = 'http://www.onlinefussballmanager.de/friendlies/annehmen_fr.php' - FRIENDLY.LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=friendly' + ORGANIZED = 'http://www.onlinefussballmanager.de/friendlies/organisierte_fr_2.php' + OFFER = 'http://www.onlinefussballmanager.de/friendlies/anbieten_fr.php' + ACCEPT = 'http://www.onlinefussballmanager.de/friendlies/annehmen_fr.php' + LINEUP = 'http://www.onlinefussballmanager.de/team/aufstellung2d.php?game=friendly' class Statistics: - pass - STATISTICS = Statistics() - STATISTICS.CLUBS = 'http://www.onlinefussballmanager.de/statistics/vereinsstatistiken.php' - STATISTICS.TEAM_STRENGTHS = 'http://www.onlinefussballmanager.de/statistics/alleteams.php' - STATISTICS.TEAM_SALARIES = 'http://www.onlinefussballmanager.de/statistics/teamgehaelter.php' - STATISTICS.STADIUMS = 'http://www.onlinefussballmanager.de/statistics/allestadien.php' - STATISTICS.TEAM_EQUITIES = 'http://www.onlinefussballmanager.de/statistics/teams_markwert.php' - STATISTICS.ETERNAL_CHART = 'http://www.onlinefussballmanager.de/statistics/ewigetabelle.php' - STATISTICS.SEARCH_ALL = 'http://www.onlinefussballmanager.de/statistics/search_all.php' - STATISTICS.SEARCH_TEAM = 'http://www.onlinefussballmanager.de/statistics/search_team.php' - STATISTICS.SEARCH_PLAYER = 'http://www.onlinefussballmanager.de/statistics/search_spieler.php' + CLUBS = 'http://www.onlinefussballmanager.de/statistics/vereinsstatistiken.php' + TEAM_STRENGTHS = 'http://www.onlinefussballmanager.de/statistics/alleteams.php' + TEAM_SALARIES = 'http://www.onlinefussballmanager.de/statistics/teamgehaelter.php' + STADIUMS = 'http://www.onlinefussballmanager.de/statistics/allestadien.php' + TEAM_EQUITIES = 'http://www.onlinefussballmanager.de/statistics/teams_markwert.php' + ETERNAL_CHART = 'http://www.onlinefussballmanager.de/statistics/ewigetabelle.php' + SEARCH_ALL = 'http://www.onlinefussballmanager.de/statistics/search_all.php' + SEARCH_TEAM = 'http://www.onlinefussballmanager.de/statistics/search_team.php' + SEARCH_PLAYER = 'http://www.onlinefussballmanager.de/statistics/search_spieler.php' class Quarters: - pass - QUARTERS = Quarters() - QUARTERS.FIRST_QUARTER_LEVELP_UP_DAY = 9 - QUARTERS.SECOND_QUARTER_LEVELP_UP_DAY = 18 - QUARTERS.THIRD_QUARTER_LEVELP_UP_DAY = 27 - QUARTERS.FOURTH_QUARTER_LEVELP_UP_DAY = 0 + FIRST_QUARTER_LEVELP_UP_DAY = 9 + SECOND_QUARTER_LEVELP_UP_DAY = 18 + THIRD_QUARTER_LEVELP_UP_DAY = 27 + FOURTH_QUARTER_LEVELP_UP_DAY = 0 class GitHub: - pass - GITHUB = GitHub() - GITHUB.LATEST_RELEASE = 'https://github.com/WiSchLabs/ofm_helper/releases/latest' + LATEST_RELEASE = 'https://github.com/WiSchLabs/ofm_helper/releases/latest' From cab7000ffe198147b0aab25ef9a5bb8bb89c1282 Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Wed, 7 Dec 2016 08:00:30 +0100 Subject: [PATCH 15/71] ignore unused arguments --- .pylintrc | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.pylintrc b/.pylintrc index f0dda5e..eaf6ba3 100644 --- a/.pylintrc +++ b/.pylintrc @@ -69,7 +69,7 @@ enable=all # --disable=W" #disable=all #disable=map-builtin-not-iterating,reduce-builtin,parameter-unpacking,buffer-builtin,raw_input-builtin,execfile-builtin,raising-string,cmp-method,old-octal-literal,suppressed-message,print-statement,import-star-module-level,indexing-exception,long-builtin,apply-builtin,dict-view-method,old-division,unicode-builtin,setslice-method,unichr-builtin,round-builtin,oct-method,next-method-called,unpacking-in-except,metaclass-assignment,using-cmp-argument,old-raise-syntax,cmp-builtin,file-builtin,old-ne-operator,basestring-builtin,xrange-builtin,useless-suppression,nonzero-method,standarderror-builtin,range-builtin-not-iterating,delslice-method,no-absolute-import,coerce-method,input-builtin,backtick,long-suffix,intern-builtin,coerce-builtin,zip-builtin-not-iterating,filter-builtin-not-iterating,reload-builtin,getslice-method,hex-method,dict-iter-method -disable=missing-docstring,unused-import,wildcard-import,unused-wildcard-import,no-method,too-few-public-methods,invalid-name,no-member,bad-continuation +disable=missing-docstring,unused-import,wildcard-import,unused-wildcard-import,no-method,too-few-public-methods,invalid-name,no-member,bad-continuation,unused-argument [REPORTS] From 8fc6a1f2cdd11d464e31ca5ee32c3cafdc37909e Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Thu, 8 Dec 2016 19:56:57 +0100 Subject: [PATCH 16/71] fix some line-to-long errors --- core/admin.py | 9 +++++---- core/models.py | 6 +++--- core/ofm_views.py | 2 +- .../stadium_stand_statistics_parser.py | 4 +++- core/parsers/stadium_statistics_parser.py | 3 ++- ...um_stand_statistics_parser_construction.py | 3 ++- .../views/test_checklist_settings_view.py | 15 ++++++++++----- core/tests/unit/views/test_settings_view.py | 3 ++- core/urls.py | 19 ++++++++++++------- core/views.py | 14 +++++--------- core/web/ofm_page_constants.py | 8 ++++---- 11 files changed, 49 insertions(+), 37 deletions(-) diff --git a/core/admin.py b/core/admin.py index 057adf8..0dfce11 100644 --- a/core/admin.py +++ b/core/admin.py @@ -1,6 +1,6 @@ -from core.models import Season, Quarter, Country, Matchday, League, Player, PlayerStatistics, Contract, Finance, Match, \ - MatchStadiumStatistics, StadiumStandStatistics, StandLevel, StadiumLevel, MatchTeamStatistics, StadiumLevelItem, \ - AwpBoundaries, Checklist, ChecklistItem +from core.models import Season, Quarter, Country, Matchday, League, Player, PlayerStatistics, Contract, Finance, \ + Match, MatchStadiumStatistics, StadiumStandStatistics, StandLevel, StadiumLevel, MatchTeamStatistics, \ + StadiumLevelItem, AwpBoundaries, Checklist, ChecklistItem from django.contrib import admin @@ -122,5 +122,6 @@ class ChecklistAdmin(admin.ModelAdmin): @admin.register(ChecklistItem) class ChecklistItemAdmin(admin.ModelAdmin): list_filter = ['checklist__user', 'name'] - list_display = ['priority', 'name', 'to_be_checked_on_matchdays', 'to_be_checked_on_matchday_pattern', 'to_be_checked_if_home_match_tomorrow'] + list_display = ['priority', 'name', 'to_be_checked_on_matchdays', 'to_be_checked_on_matchday_pattern', + 'to_be_checked_if_home_match_tomorrow'] search_fields = ['checklist__user__username', 'name'] diff --git a/core/models.py b/core/models.py index 0ad4664..40dd52f 100644 --- a/core/models.py +++ b/core/models.py @@ -781,11 +781,11 @@ def get_from_matchday(matchday): @staticmethod def _name_from_matchday(matchday): - if Constants.Quarters.FOURTH_QUARTER_LEVELP_UP_DAY <= matchday.number < Constants.Quarters.FIRST_QUARTER_LEVELP_UP_DAY: + if Constants.Quarters.FOURTH_QUARTER_LEVEL_UP_DAY <= matchday.number < Constants.Quarters.FIRST_QUARTER_LEVEL_UP_DAY: return 'awp_boundaries_' + str(matchday.season.number) + '_0' - elif Constants.Quarters.FIRST_QUARTER_LEVELP_UP_DAY <= matchday.number < Constants.Quarters.SECOND_QUARTER_LEVELP_UP_DAY: + elif Constants.Quarters.FIRST_QUARTER_LEVEL_UP_DAY <= matchday.number < Constants.Quarters.SECOND_QUARTER_LEVEL_UP_DAY: return 'awp_boundaries_' + str(matchday.season.number) + '_1' - elif Constants.Quarters.SECOND_QUARTER_LEVELP_UP_DAY <= matchday.number < Constants.Quarters.THIRD_QUARTER_LEVELP_UP_DAY: + elif Constants.Quarters.SECOND_QUARTER_LEVEL_UP_DAY <= matchday.number < Constants.Quarters.THIRD_QUARTER_LEVEL_UP_DAY: return 'awp_boundaries_' + str(matchday.season.number) + '_2' else: return 'awp_boundaries_' + str(matchday.season.number) + '_3' diff --git a/core/ofm_views.py b/core/ofm_views.py index bdd9877..ababe3e 100644 --- a/core/ofm_views.py +++ b/core/ofm_views.py @@ -60,7 +60,7 @@ def get(self, request, *args, **kwargs): player_statistics_json = [ self._get_player_statistics_diff_in_json(newer_player_statistics, older_player_statistics) for (newer_player_statistics, older_player_statistics) in player_statistics_tuples - ] + ] return self.render_json_response(player_statistics_json) diff --git a/core/parsers/stadium_stand_statistics_parser.py b/core/parsers/stadium_stand_statistics_parser.py index 40881db..526d3b8 100644 --- a/core/parsers/stadium_stand_statistics_parser.py +++ b/core/parsers/stadium_stand_statistics_parser.py @@ -45,7 +45,9 @@ def _parse_stand_statistics(self, stand_data): condition = 100 if 'Stadionzustand' in stand_data.find_all('tr')[2].find_all('td')[0].find_all('span')[0].get_text(): # the condition during match is only known, if the stand is NOT set under construction AFTER the game - condition = stand_data.find_all('tr')[2].find_all('td')[0].find_all('span')[1].get_text().replace(',', '.').replace('%', '') + condition = stand_data.find_all('tr')[2].find_all('td')[0].find_all('span')[1].get_text().replace(',', + '.').replace( + '%', '') ticket_price = stand_data.find_all('tr')[6].find_all('select')[0].find('option', selected=True).get('value') stand_level, _ = StandLevel.objects.get_or_create( diff --git a/core/parsers/stadium_statistics_parser.py b/core/parsers/stadium_statistics_parser.py index b8ee5de..2616ab8 100644 --- a/core/parsers/stadium_statistics_parser.py +++ b/core/parsers/stadium_statistics_parser.py @@ -29,7 +29,8 @@ def parse_html(self, soup): last_stadium_level = None if last_home_matches.count() > 0: # only consider matches statistics BEFORE current match - last_home_matches = [match for match in last_home_matches if match.matchday.number <= self.match.matchday.number] + last_home_matches = [match for match in last_home_matches if + match.matchday.number <= self.match.matchday.number] last_home_match = last_home_matches[0] last_stadium_level = MatchStadiumStatistics.objects.filter(match=last_home_match)[0].level diff --git a/core/tests/unit/parser/test_stadium_stand_statistics_parser_construction.py b/core/tests/unit/parser/test_stadium_stand_statistics_parser_construction.py index e34261e..6d75b7d 100644 --- a/core/tests/unit/parser/test_stadium_stand_statistics_parser_construction.py +++ b/core/tests/unit/parser/test_stadium_stand_statistics_parser_construction.py @@ -12,7 +12,8 @@ class StadiumStandStatisticsParserTest(TestCase): def setUp(self): - testdata = open(os.path.join(TESTDATA_PATH, 'stadium_overview_special_construction_and_repair.html'), encoding='utf8') + testdata = open(os.path.join(TESTDATA_PATH, 'stadium_overview_special_construction_and_repair.html'), + encoding='utf8') self.user = OFMUserFactory.create(username='IsaacAsimov') self.match = MatchFactory.create(user=self.user) MatchStadiumStatisticsFactory.create(match=self.match) diff --git a/core/tests/unit/views/test_checklist_settings_view.py b/core/tests/unit/views/test_checklist_settings_view.py index e0460c9..f4f4f2f 100644 --- a/core/tests/unit/views/test_checklist_settings_view.py +++ b/core/tests/unit/views/test_checklist_settings_view.py @@ -90,7 +90,8 @@ def test_update_checklist_item_home_match(self): self.assertEqual(returned_json_data[0]['type_home_match'], True) self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_on_matchdays, None) self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_on_matchday_pattern, None) - self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_if_home_match_tomorrow, True) + self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_if_home_match_tomorrow, + True) def test_update_checklist_item_matchday(self): self.client.login(username='temporary', password='temporary') @@ -111,7 +112,8 @@ def test_update_checklist_item_matchday(self): self.assertEqual(returned_json_data[0]['type_matchdays'], '4') self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_on_matchdays, "4") self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_on_matchday_pattern, None) - self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_if_home_match_tomorrow, False) + self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_if_home_match_tomorrow, + False) def test_update_checklist_item_matchdays(self): self.client.login(username='temporary', password='temporary') @@ -132,7 +134,8 @@ def test_update_checklist_item_matchdays(self): self.assertEqual(returned_json_data[0]['type_matchdays'], '3,33') self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_on_matchdays, "3,33") self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_on_matchday_pattern, None) - self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_if_home_match_tomorrow, False) + self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_if_home_match_tomorrow, + False) def test_update_checklist_item_matchday_pattern(self): self.client.login(username='temporary', password='temporary') @@ -153,7 +156,8 @@ def test_update_checklist_item_matchday_pattern(self): self.assertEqual(returned_json_data[0]['type_matchday_pattern'], 2) self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_on_matchdays, None) self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_on_matchday_pattern, 2) - self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_if_home_match_tomorrow, False) + self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_if_home_match_tomorrow, + False) def test_update_checklist_item_everyday(self): self.client.login(username='temporary', password='temporary') @@ -173,7 +177,8 @@ def test_update_checklist_item_everyday(self): self.assertFalse('type_home_match' in returned_json_data[0]) self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_on_matchdays, None) self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_on_matchday_pattern, None) - self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_if_home_match_tomorrow, False) + self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).to_be_checked_if_home_match_tomorrow, + False) def test_update_checklist_item_checked(self): self.client.login(username='temporary', password='temporary') diff --git a/core/tests/unit/views/test_settings_view.py b/core/tests/unit/views/test_settings_view.py index 7d8a1b7..7014a2b 100644 --- a/core/tests/unit/views/test_settings_view.py +++ b/core/tests/unit/views/test_settings_view.py @@ -59,7 +59,8 @@ def test_change_password(self): def test_change_ofm_password(self): self.client.login(username='temporary', password='temporary') - response = self.client.post(reverse('core:settings'), {'ofm_password': 'Zillertal', 'ofm_password2': 'Zillertal'}) + response = self.client.post(reverse('core:settings'), + {'ofm_password': 'Zillertal', 'ofm_password2': 'Zillertal'}) self.assertEqual(response.status_code, 200) self.assertTemplateUsed(response, 'core/account/settings.html') self.assertTrue(response.wsgi_request.user.is_authenticated()) diff --git a/core/urls.py b/core/urls.py index cbd94ac..2086704 100644 --- a/core/urls.py +++ b/core/urls.py @@ -2,8 +2,8 @@ from django.views.generic.base import TemplateView, RedirectView from core import views -from core.views import CreateChecklistItemView, DeleteChecklistItemView, GetChecklistItemsView, UpdateChecklistItemView, \ - GetChecklistItemsForTodayView, GetCurrentMatchdayView, UpdateChecklistPriorityView +from core.views import CreateChecklistItemView, DeleteChecklistItemView, GetChecklistItemsView, \ + UpdateChecklistItemView, GetChecklistItemsForTodayView, GetCurrentMatchdayView, UpdateChecklistPriorityView app_name = 'core' urlpatterns = [ @@ -18,16 +18,21 @@ url(r'^settings/?$', views.settings_view, name='settings'), url(r'^settings_get_checklist_items/?$', GetChecklistItemsView.as_view(), name='settings_get_checklist_items'), - url(r'^settings_get_checklist_items_for_today/?$', GetChecklistItemsForTodayView.as_view(), name='settings_get_checklist_items_for_today'), + url(r'^settings_get_checklist_items_for_today/?$', GetChecklistItemsForTodayView.as_view(), + name='settings_get_checklist_items_for_today'), url(r'^settings_add_checklist_item/?$', CreateChecklistItemView.as_view(), name='settings_add_checklist_item'), - url(r'^settings_update_checklist_item/?$', UpdateChecklistItemView.as_view(), name='settings_update_checklist_item'), - url(r'^settings_delete_checklist_item/?$', DeleteChecklistItemView.as_view(), name='settings_delete_checklist_item'), - url(r'^settings_update_checklist_priority/?$', UpdateChecklistPriorityView.as_view(), name='settings_update_checklist_priority'), + url(r'^settings_update_checklist_item/?$', UpdateChecklistItemView.as_view(), + name='settings_update_checklist_item'), + url(r'^settings_delete_checklist_item/?$', DeleteChecklistItemView.as_view(), + name='settings_delete_checklist_item'), + url(r'^settings_update_checklist_priority/?$', UpdateChecklistPriorityView.as_view(), + name='settings_update_checklist_priority'), url(r'^trigger_parsing/?$', views.trigger_parsing, name='trigger_parsing'), url(r'^trigger_matchday_parsing/?$', views.trigger_matchday_parsing, name='trigger_matchday_parsing'), url(r'^trigger_players_parsing/?$', views.trigger_players_parsing, name='trigger_players_parsing'), - url(r'^trigger_player_statistics_parsing/?$', views.trigger_player_statistics_parsing, name='trigger_player_statistics_parsing'), + url(r'^trigger_player_statistics_parsing/?$', views.trigger_player_statistics_parsing, + name='trigger_player_statistics_parsing'), url(r'^trigger_finances_parsing/?$', views.trigger_finances_parsing, name='trigger_finances_parsing'), url(r'^trigger_match_parsing/?$', views.trigger_match_parsing, name='trigger_match_parsing'), ] diff --git a/core/views.py b/core/views.py index 6790b56..a716f05 100644 --- a/core/views.py +++ b/core/views.py @@ -138,7 +138,6 @@ def settings_view(request): @method_decorator(login_required, name='dispatch') class GetCurrentMatchdayView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): current_matchday = Matchday.get_current() matchday_json = dict() @@ -149,7 +148,6 @@ def get(self, request, *args, **kwargs): @method_decorator(login_required, name='dispatch') class GetChecklistItemsView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): checklist_items = ChecklistItem.objects.filter(checklist__user=request.user) @@ -160,7 +158,6 @@ def get(self, request, *args, **kwargs): @method_decorator(login_required, name='dispatch') class GetChecklistItemsForTodayView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): current_matchday = Matchday.get_current() next_matchday_number = current_matchday.number + 1 @@ -183,7 +180,9 @@ def get(self, request, *args, **kwargs): to_be_checked_on_matchday_pattern=None, to_be_checked_if_home_match_tomorrow=False ) - filtered_checklist_items.extend([c for c in checklist_items_this_matchday if current_matchday.number in [int(x) for x in c.to_be_checked_on_matchdays.split(',')]]) + filtered_checklist_items.extend([c for c in checklist_items_this_matchday if + current_matchday.number in [int(x) for x in + c.to_be_checked_on_matchdays.split(',')]]) if home_match_tomorrow: checklist_items_home_match = checklist_items.filter( to_be_checked_on_matchdays=None, @@ -225,7 +224,6 @@ def _get_checklist_item_in_json(checklist_item): @method_decorator(login_required, name='dispatch') class CreateChecklistItemView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): checklist, _ = Checklist.objects.get_or_create(user=request.user) new_checklist_item = ChecklistItem.objects.create(checklist=checklist, name='Neuer Eintrag') @@ -237,7 +235,6 @@ def get(self, request, *args, **kwargs): @method_decorator(login_required, name='dispatch') class UpdateChecklistPriorityView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def post(self, request, *args, **kwargs): checklist_priority = request.POST.get('checklist_priority') @@ -252,7 +249,6 @@ def post(self, request, *args, **kwargs): @method_decorator(login_required, name='dispatch') class UpdateChecklistItemView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def post(self, request, *args, **kwargs): checklist_item_id = request.POST.get('checklist_item_id') checklist_item_name = request.POST.get('checklist_item_name') @@ -294,7 +290,6 @@ def post(self, request, *args, **kwargs): @method_decorator(login_required, name='dispatch') class DeleteChecklistItemView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def post(self, request, *args, **kwargs): checklist_item_id = request.POST.get('checklist_item_id') checklist_item = ChecklistItem.objects.get(checklist__user=request.user, id=checklist_item_id) @@ -332,7 +327,8 @@ def trigger_parsing(request): with open('version', 'r') as version_file: own_version = version_file.read().replace('\n', '') if own_version != "null" and own_version != remote_version: - messages.info(request, "Es ist eine neuere Version von OFM Helper verfügbar: %s. Du nutzt noch: %s." % (remote_version, own_version)) + messages.info(request, "Es ist eine neuere Version von OFM Helper verfügbar: %s. Du nutzt noch: %s." % ( + remote_version, own_version)) except IOError: pass diff --git a/core/web/ofm_page_constants.py b/core/web/ofm_page_constants.py index 3827af0..45e3110 100644 --- a/core/web/ofm_page_constants.py +++ b/core/web/ofm_page_constants.py @@ -97,10 +97,10 @@ class Statistics: SEARCH_PLAYER = 'http://www.onlinefussballmanager.de/statistics/search_spieler.php' class Quarters: - FIRST_QUARTER_LEVELP_UP_DAY = 9 - SECOND_QUARTER_LEVELP_UP_DAY = 18 - THIRD_QUARTER_LEVELP_UP_DAY = 27 - FOURTH_QUARTER_LEVELP_UP_DAY = 0 + FIRST_QUARTER_LEVEL_UP_DAY = 9 + SECOND_QUARTER_LEVEL_UP_DAY = 18 + THIRD_QUARTER_LEVEL_UP_DAY = 27 + FOURTH_QUARTER_LEVEL_UP_DAY = 0 class GitHub: LATEST_RELEASE = 'https://github.com/WiSchLabs/ofm_helper/releases/latest' From 9fc26af334c665edc8f402ec0496153c5f6d18e7 Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Thu, 8 Dec 2016 20:29:46 +0100 Subject: [PATCH 17/71] Call abstract base class constructor Taken from: https://docs.python.org/2/library/abc.html --- core/parsers/awp_boundaries_parser.py | 1 + core/parsers/base_parser.py | 6 ++++++ core/parsers/finances_parser.py | 1 + core/parsers/future_match_row_parser.py | 1 + core/parsers/match_parser.py | 1 + core/parsers/matchday_parser.py | 1 + core/parsers/ofm_helper_version_parser.py | 1 + core/parsers/player_statistics_parser.py | 1 + core/parsers/players_parser.py | 1 + core/parsers/stadium_stand_statistics_parser.py | 2 +- core/parsers/stadium_statistics_parser.py | 1 + core/parsers/won_by_default_match_row_parser.py | 1 + 12 files changed, 17 insertions(+), 1 deletion(-) diff --git a/core/parsers/awp_boundaries_parser.py b/core/parsers/awp_boundaries_parser.py index 8d44fae..4be9975 100644 --- a/core/parsers/awp_boundaries_parser.py +++ b/core/parsers/awp_boundaries_parser.py @@ -10,6 +10,7 @@ class AwpBoundariesParser(BaseParser): def __init__(self, html_source, user, matchday): + super(AwpBoundariesParser, self).__init__() self.html_source = html_source self.user = user self.matchday = matchday diff --git a/core/parsers/base_parser.py b/core/parsers/base_parser.py index aa7cb8b..59eb125 100644 --- a/core/parsers/base_parser.py +++ b/core/parsers/base_parser.py @@ -1,4 +1,10 @@ +import abc + + class BaseParser: + __metaclass__ = abc.ABCMeta + + @abc.abstractmethod def __init__(self): self.html_source = '' diff --git a/core/parsers/finances_parser.py b/core/parsers/finances_parser.py index 271be3a..2ec10d4 100644 --- a/core/parsers/finances_parser.py +++ b/core/parsers/finances_parser.py @@ -10,6 +10,7 @@ class FinancesParser(BaseParser): def __init__(self, html_source, user, matchday): + super(FinancesParser, self).__init__() self.html_source = html_source self.user = user self.matchday = matchday diff --git a/core/parsers/future_match_row_parser.py b/core/parsers/future_match_row_parser.py index f4fd598..06baf71 100644 --- a/core/parsers/future_match_row_parser.py +++ b/core/parsers/future_match_row_parser.py @@ -10,6 +10,7 @@ class FutureMatchRowParser(BaseParser): def __init__(self, html_source, user): + super(FutureMatchRowParser, self).__init__() self.html_source = html_source self.user = user diff --git a/core/parsers/match_parser.py b/core/parsers/match_parser.py index 899c1f5..d578f36 100644 --- a/core/parsers/match_parser.py +++ b/core/parsers/match_parser.py @@ -11,6 +11,7 @@ class MatchParser(BaseParser): def __init__(self, html_source, user, is_home_match): + super(MatchParser, self).__init__() self.html_source = html_source self.user = user self.is_home_match = is_home_match diff --git a/core/parsers/matchday_parser.py b/core/parsers/matchday_parser.py index ab26556..372757f 100644 --- a/core/parsers/matchday_parser.py +++ b/core/parsers/matchday_parser.py @@ -10,6 +10,7 @@ class MatchdayParser(BaseParser): def __init__(self, html_source): + super(MatchdayParser, self).__init__() self.html_source = html_source def parse(self): diff --git a/core/parsers/ofm_helper_version_parser.py b/core/parsers/ofm_helper_version_parser.py index cdf1581..d6330c2 100644 --- a/core/parsers/ofm_helper_version_parser.py +++ b/core/parsers/ofm_helper_version_parser.py @@ -8,6 +8,7 @@ class OfmHelperVersionParser(BaseParser): def __init__(self, html_source): + super(OfmHelperVersionParser, self).__init__() self.html_source = html_source def parse(self): diff --git a/core/parsers/player_statistics_parser.py b/core/parsers/player_statistics_parser.py index b03cf4a..63d9c76 100644 --- a/core/parsers/player_statistics_parser.py +++ b/core/parsers/player_statistics_parser.py @@ -12,6 +12,7 @@ class PlayerStatisticsParser(BaseParser): def __init__(self, html_source, user, matchday): + super(PlayerStatisticsParser, self).__init__() self.html_source = html_source self.user = user self.matchday = matchday diff --git a/core/parsers/players_parser.py b/core/parsers/players_parser.py index 69469e3..2d444f8 100644 --- a/core/parsers/players_parser.py +++ b/core/parsers/players_parser.py @@ -10,6 +10,7 @@ class PlayersParser(BaseParser): def __init__(self, html_source, user, matchday): + super(PlayersParser, self).__init__() self.html_source = html_source self.user = user self.matchday = matchday diff --git a/core/parsers/stadium_stand_statistics_parser.py b/core/parsers/stadium_stand_statistics_parser.py index 526d3b8..fa4cf39 100644 --- a/core/parsers/stadium_stand_statistics_parser.py +++ b/core/parsers/stadium_stand_statistics_parser.py @@ -10,9 +10,9 @@ class StadiumStandStatisticsParser(BaseParser): def __init__(self, html_source, user, match): + super(StadiumStandStatisticsParser, self).__init__() self.html_source = html_source self.user = user - self.match_stadium_stat = MatchStadiumStatistics.objects.filter(match=match)[0] def parse(self): diff --git a/core/parsers/stadium_statistics_parser.py b/core/parsers/stadium_statistics_parser.py index 2616ab8..16d6f64 100644 --- a/core/parsers/stadium_statistics_parser.py +++ b/core/parsers/stadium_statistics_parser.py @@ -10,6 +10,7 @@ class StadiumStatisticsParser(BaseParser): def __init__(self, html_source, user, match): + super(StadiumStatisticsParser, self).__init__() self.html_source = html_source self.user = user self.match = match diff --git a/core/parsers/won_by_default_match_row_parser.py b/core/parsers/won_by_default_match_row_parser.py index 807c982..d6651a5 100644 --- a/core/parsers/won_by_default_match_row_parser.py +++ b/core/parsers/won_by_default_match_row_parser.py @@ -10,6 +10,7 @@ class WonByDefaultMatchRowParser(BaseParser): def __init__(self, html_source, user): + super(WonByDefaultMatchRowParser, self).__init__() self.html_source = html_source self.user = user From f68374268f6959166131ec8d042729d81a5e7c53 Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Thu, 8 Dec 2016 21:40:37 +0100 Subject: [PATCH 18/71] use lazy logging string formatting --- core/parsers/finances_parser.py | 2 +- core/parsers/matchday_parser.py | 2 +- core/parsers/ofm_helper_version_parser.py | 2 +- core/parsers/player_statistics_parser.py | 2 +- core/parsers/players_parser.py | 2 +- 5 files changed, 5 insertions(+), 5 deletions(-) diff --git a/core/parsers/finances_parser.py b/core/parsers/finances_parser.py index 2ec10d4..0626a3f 100644 --- a/core/parsers/finances_parser.py +++ b/core/parsers/finances_parser.py @@ -56,7 +56,7 @@ def parse_html(self, soup): user=self.user, matchday=self.matchday, ) - logger.debug('===== Finance parsed: %s' % finances) + logger.debug('===== Finance parsed: %s', finances) finances.balance = balance finances.income_visitors_league = income_visitors_league diff --git a/core/parsers/matchday_parser.py b/core/parsers/matchday_parser.py index 372757f..6bb3228 100644 --- a/core/parsers/matchday_parser.py +++ b/core/parsers/matchday_parser.py @@ -29,6 +29,6 @@ def parse(self): matchday.season.save() matchday.save() - logger.debug('===== Matchday parsed: {} '.format(matchday)) + logger.debug('===== Matchday parsed: %s', matchday) return matchday diff --git a/core/parsers/ofm_helper_version_parser.py b/core/parsers/ofm_helper_version_parser.py index d6330c2..5b99a7e 100644 --- a/core/parsers/ofm_helper_version_parser.py +++ b/core/parsers/ofm_helper_version_parser.py @@ -14,6 +14,6 @@ def __init__(self, html_source): def parse(self): soup = BeautifulSoup(self.html_source, "html.parser") version = soup.find_all(class_='tag-references')[0].find_all(class_='css-truncate-target')[0].get_text() - logger.debug('===== OFM Helper version parsed: %s ' % version) + logger.debug('===== OFM Helper version parsed: %s ', version) return version diff --git a/core/parsers/player_statistics_parser.py b/core/parsers/player_statistics_parser.py index 63d9c76..0155f3d 100644 --- a/core/parsers/player_statistics_parser.py +++ b/core/parsers/player_statistics_parser.py @@ -62,7 +62,7 @@ def parse_row(self, player_row): matchday=self.matchday, player=player ) - logger.debug('===== PlayerStatistics parsed: %s' % parsed_player_stat) + logger.debug('===== PlayerStatistics parsed: %s', parsed_player_stat) parsed_player_stat.strength = strength parsed_player_stat.games_in_season = games_in_season diff --git a/core/parsers/players_parser.py b/core/parsers/players_parser.py index 2d444f8..6749b5b 100644 --- a/core/parsers/players_parser.py +++ b/core/parsers/players_parser.py @@ -52,7 +52,7 @@ def parse_row(self, player_row): player.name = name player.save() - logger.debug('===== Player parsed: %s' % player.name) + logger.debug('===== Player parsed: %s', player.name) self._create_contract(player) logger.debug('===== Contract created.') From f059db1e05a8529ba645b530b30eb33bc629ae29 Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Fri, 9 Dec 2016 16:27:56 +0100 Subject: [PATCH 19/71] fix some more too long lines --- core/ofm_urls.py | 3 ++- core/ofm_views.py | 6 ++++-- core/parsers/stadium_stand_statistics_parser.py | 7 ++++--- 3 files changed, 10 insertions(+), 6 deletions(-) diff --git a/core/ofm_urls.py b/core/ofm_urls.py index bed02de..a7f9832 100644 --- a/core/ofm_urls.py +++ b/core/ofm_urls.py @@ -26,5 +26,6 @@ url(r'^stadium_statistics_json/?$', StadiumStatisticsAsJsonView.as_view(), name='stadium_statistics_overview_json'), url(r'^stadium/(?P[0-9]+)/?$', StadiumDetailView.as_view(), name='stadium_detail'), url(r'^stadium_stand/?$', StadiumStandStatisticsView.as_view(), name='stadium_stand_statistics'), - url(r'^stadium_stand_chart_json/?$', StadiumStandStatisticsChartView.as_view(), name='stadium_stand_statistics_chart_json'), + url(r'^stadium_stand_chart_json/?$', StadiumStandStatisticsChartView.as_view(), + name='stadium_stand_statistics_chart_json'), ] diff --git a/core/ofm_views.py b/core/ofm_views.py index ababe3e..1ffc8f1 100644 --- a/core/ofm_views.py +++ b/core/ofm_views.py @@ -286,7 +286,8 @@ def _get_finances_diff_in_json(self, newer_finances, older_finances): income_visitors_friendlies = newer_finances.income_visitors_friendlies if older_finances: - income_visitors_friendlies = newer_finances.income_visitors_friendlies - older_finances.income_visitors_friendlies + income_visitors_friendlies = newer_finances.income_visitors_friendlies - \ + older_finances.income_visitors_friendlies income_friendlies = newer_finances.income_friendlies if older_finances: @@ -764,7 +765,8 @@ def _get_stadium_statistics_in_json(self, stadium_stat): match_stadium_stat['capacity'] = stadium_stat.capacity match_stadium_stat['earnings'] = stadium_stat.earnings match_stadium_stat['workload'] = locale.format("%.2f", - stadium_stat.visitors / stadium_stat.capacity * 100) + " %" + stadium_stat.visitors / + stadium_stat.capacity * 100) + " %" else: # all stadium stands were under construction during match match_stadium_stat['visitors'] = 0 diff --git a/core/parsers/stadium_stand_statistics_parser.py b/core/parsers/stadium_stand_statistics_parser.py index fa4cf39..d4fcb3a 100644 --- a/core/parsers/stadium_stand_statistics_parser.py +++ b/core/parsers/stadium_stand_statistics_parser.py @@ -45,9 +45,10 @@ def _parse_stand_statistics(self, stand_data): condition = 100 if 'Stadionzustand' in stand_data.find_all('tr')[2].find_all('td')[0].find_all('span')[0].get_text(): # the condition during match is only known, if the stand is NOT set under construction AFTER the game - condition = stand_data.find_all('tr')[2].find_all('td')[0].find_all('span')[1].get_text().replace(',', - '.').replace( - '%', '') + condition = stand_data\ + .find_all('tr')[2].find_all('td')[0].find_all('span')[1].get_text()\ + .replace(',', '.')\ + .replace('%', '') ticket_price = stand_data.find_all('tr')[6].find_all('select')[0].find('option', selected=True).get('value') stand_level, _ = StandLevel.objects.get_or_create( From 587124f0d02da273066349e63fabe2b07d4971eb Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Fri, 9 Dec 2016 16:51:39 +0100 Subject: [PATCH 20/71] ignore var redifition + fix some obvious stuff --- .pylintrc | 2 +- core/managers/parser_manager.py | 6 ++---- core/parsers/ofm_helper_version_parser.py | 3 ++- 3 files changed, 5 insertions(+), 6 deletions(-) diff --git a/.pylintrc b/.pylintrc index eaf6ba3..403a733 100644 --- a/.pylintrc +++ b/.pylintrc @@ -69,7 +69,7 @@ enable=all # --disable=W" #disable=all #disable=map-builtin-not-iterating,reduce-builtin,parameter-unpacking,buffer-builtin,raw_input-builtin,execfile-builtin,raising-string,cmp-method,old-octal-literal,suppressed-message,print-statement,import-star-module-level,indexing-exception,long-builtin,apply-builtin,dict-view-method,old-division,unicode-builtin,setslice-method,unichr-builtin,round-builtin,oct-method,next-method-called,unpacking-in-except,metaclass-assignment,using-cmp-argument,old-raise-syntax,cmp-builtin,file-builtin,old-ne-operator,basestring-builtin,xrange-builtin,useless-suppression,nonzero-method,standarderror-builtin,range-builtin-not-iterating,delslice-method,no-absolute-import,coerce-method,input-builtin,backtick,long-suffix,intern-builtin,coerce-builtin,zip-builtin-not-iterating,filter-builtin-not-iterating,reload-builtin,getslice-method,hex-method,dict-iter-method -disable=missing-docstring,unused-import,wildcard-import,unused-wildcard-import,no-method,too-few-public-methods,invalid-name,no-member,bad-continuation,unused-argument +disable=missing-docstring,unused-import,wildcard-import,unused-wildcard-import,no-method,too-few-public-methods,invalid-name,no-member,bad-continuation,unused-argument,redefined-variable-type [REPORTS] diff --git a/core/managers/parser_manager.py b/core/managers/parser_manager.py index 682a7df..44ecd1f 100644 --- a/core/managers/parser_manager.py +++ b/core/managers/parser_manager.py @@ -104,11 +104,9 @@ def _parse_single_match(self, request, site_manager, row): return match elif "-:-" in match_result: # match is scheduled, but did not take place yet - match_parser = FutureMatchRowParser(row, request.user) - return match_parser.parse() + return FutureMatchRowParser(row, request.user).parse() else: - match_parser = WonByDefaultMatchRowParser(row, request.user) - return match_parser.parse() + return WonByDefaultMatchRowParser(row, request.user).parse() def _parse_stadium_statistics(self, request, site_manager, match): site_manager.jump_to_frame(Constants.Stadium.ENVIRONMENT) diff --git a/core/parsers/ofm_helper_version_parser.py b/core/parsers/ofm_helper_version_parser.py index 5b99a7e..14da0ed 100644 --- a/core/parsers/ofm_helper_version_parser.py +++ b/core/parsers/ofm_helper_version_parser.py @@ -1,7 +1,8 @@ +import logging + from bs4 import BeautifulSoup from core.parsers.base_parser import BaseParser -import logging logger = logging.getLogger(__name__) From 326053bcbda30d5d7d551b5ffd03376ab9c0b88c Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Sat, 10 Dec 2016 16:35:37 +0100 Subject: [PATCH 21/71] set max linelength to 120 --- .editorconfig | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/.editorconfig b/.editorconfig index 5bfc5e4..26c3c62 100644 --- a/.editorconfig +++ b/.editorconfig @@ -5,6 +5,7 @@ root = true [*] charset = utf-8 end_of_line = lf +max_line_length=120 insert_final_newline = true trim_trailing_whitespace = true @@ -14,4 +15,4 @@ indent_size = 4 [*.yml] indent_style = space -indent_size = 2 \ No newline at end of file +indent_size = 2 From da5afbd8b9b97de0e252cffe07787e53a8bcce85 Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Sat, 10 Dec 2016 17:28:13 +0100 Subject: [PATCH 22/71] ignore specific too long lines --- core/models.py | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/core/models.py b/core/models.py index 40dd52f..1c978cb 100644 --- a/core/models.py +++ b/core/models.py @@ -781,11 +781,11 @@ def get_from_matchday(matchday): @staticmethod def _name_from_matchday(matchday): - if Constants.Quarters.FOURTH_QUARTER_LEVEL_UP_DAY <= matchday.number < Constants.Quarters.FIRST_QUARTER_LEVEL_UP_DAY: + if Constants.Quarters.FOURTH_QUARTER_LEVEL_UP_DAY <= matchday.number < Constants.Quarters.FIRST_QUARTER_LEVEL_UP_DAY: # pylint: disable=line-too-long return 'awp_boundaries_' + str(matchday.season.number) + '_0' - elif Constants.Quarters.FIRST_QUARTER_LEVEL_UP_DAY <= matchday.number < Constants.Quarters.SECOND_QUARTER_LEVEL_UP_DAY: + elif Constants.Quarters.FIRST_QUARTER_LEVEL_UP_DAY <= matchday.number < Constants.Quarters.SECOND_QUARTER_LEVEL_UP_DAY: # pylint: disable=line-too-long return 'awp_boundaries_' + str(matchday.season.number) + '_1' - elif Constants.Quarters.SECOND_QUARTER_LEVEL_UP_DAY <= matchday.number < Constants.Quarters.THIRD_QUARTER_LEVEL_UP_DAY: + elif Constants.Quarters.SECOND_QUARTER_LEVEL_UP_DAY <= matchday.number < Constants.Quarters.THIRD_QUARTER_LEVEL_UP_DAY: # pylint: disable=line-too-long return 'awp_boundaries_' + str(matchday.season.number) + '_2' else: return 'awp_boundaries_' + str(matchday.season.number) + '_3' From 2cd6997e9b452337241c378b00bcc003d9918c9c Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Sat, 10 Dec 2016 17:59:43 +0100 Subject: [PATCH 23/71] #99 refactored some pylint warnings --- core/models.py | 6 ++- core/parsers/finances_parser.py | 67 +++++++++---------------- core/parsers/future_match_row_parser.py | 7 +-- core/parsers/players_parser.py | 2 +- 4 files changed, 33 insertions(+), 49 deletions(-) diff --git a/core/models.py b/core/models.py index 1c978cb..9e84404 100644 --- a/core/models.py +++ b/core/models.py @@ -276,6 +276,10 @@ def __str__(self): def get_iso(self): return self.country + @staticmethod + def get_choices(): + return dict(Country._meta.get_field('country').choices) + class League(models.Model): LEAGUES = ( @@ -297,7 +301,7 @@ class League(models.Model): country = models.ForeignKey(Country) def __str__(self): - return "%s %s (%s)" % (self.LEAGUES[self.league][1], self.relay, self.country) + return "%s %s (%s)" % (self.LEAGUES[self.league][1], self.relay, self.country) # pylint: disable=invalid-sequence-index class Player(models.Model): diff --git a/core/parsers/finances_parser.py b/core/parsers/finances_parser.py index 0626a3f..decb55b 100644 --- a/core/parsers/finances_parser.py +++ b/core/parsers/finances_parser.py @@ -28,29 +28,6 @@ def parse_html(self, soup): finance_table = soup.find(id="einaus").find_all('table')[2] finance_values = finance_table.find_all('tr') - balance = self._int_from_money(finance_values[25].find_all('td')[5].get_text()) - - income_visitors_league = self._int_from_money(finance_values[4].find_all('td')[3].div.get_text()) - income_sponsoring = self._int_from_money(finance_values[5].find_all('td')[3].div.get_text()) - income_cup = self._int_from_money(finance_values[6].find_all('td')[3].div.get_text()) - income_interests = self._int_from_money(finance_values[7].find_all('td')[3].div.get_text()) - income_loan = self._int_from_money(finance_values[8].find_all('td')[3].div.get_text()) - income_transfer = self._int_from_money(finance_values[9].find_all('td')[3].div.get_text()) - income_visitors_friendlies = self._int_from_money(finance_values[10].find_all('td')[3].div.get_text()) - income_friendlies = self._int_from_money(finance_values[11].find_all('td')[3].div.get_text()) - income_funcup = self._int_from_money(finance_values[12].find_all('td')[3].div.get_text()) - income_betting = self._int_from_money(finance_values[13].find_all('td')[3].div.get_text()) - - expenses_player_salaries = self._int_from_money(finance_values[4].find_all('td')[11].div.get_text()) - expenses_stadium = self._int_from_money(finance_values[5].find_all('td')[11].div.get_text()) - expenses_youth = self._int_from_money(finance_values[6].find_all('td')[11].div.get_text()) - expenses_interests = self._int_from_money(finance_values[7].find_all('td')[11].div.get_text()) - expenses_trainings = self._int_from_money(finance_values[8].find_all('td')[11].div.get_text()) - expenses_transfer = self._int_from_money(finance_values[9].find_all('td')[11].div.get_text()) - expenses_compensation = self._int_from_money(finance_values[10].find_all('td')[11].div.get_text()) - expenses_friendlies = self._int_from_money(finance_values[11].find_all('td')[11].div.get_text()) - expenses_funcup = self._int_from_money(finance_values[12].find_all('td')[11].div.get_text()) - expenses_betting = self._int_from_money(finance_values[13].find_all('td')[11].div.get_text()) finances, _ = Finance.objects.get_or_create( user=self.user, @@ -58,27 +35,29 @@ def parse_html(self, soup): ) logger.debug('===== Finance parsed: %s', finances) - finances.balance = balance - finances.income_visitors_league = income_visitors_league - finances.income_sponsoring = income_sponsoring - finances.income_cup = income_cup - finances.income_interests = income_interests - finances.income_loan = income_loan - finances.income_transfer = income_transfer - finances.income_visitors_friendlies = income_visitors_friendlies - finances.income_friendlies = income_friendlies - finances.income_funcup = income_funcup - finances.income_betting = income_betting - finances.expenses_player_salaries = expenses_player_salaries - finances.expenses_stadium = expenses_stadium - finances.expenses_youth = expenses_youth - finances.expenses_interests = expenses_interests - finances.expenses_trainings = expenses_trainings - finances.expenses_transfer = expenses_transfer - finances.expenses_compensation = expenses_compensation - finances.expenses_friendlies = expenses_friendlies - finances.expenses_funcup = expenses_funcup - finances.expenses_betting = expenses_betting + finances.balance = self._int_from_money(finance_values[25].find_all('td')[5].get_text()) + + finances.income_visitors_league = self._int_from_money(finance_values[4].find_all('td')[3].div.get_text()) + finances.income_sponsoring = self._int_from_money(finance_values[5].find_all('td')[3].div.get_text()) + finances.income_cup = self._int_from_money(finance_values[6].find_all('td')[3].div.get_text()) + finances.income_interests = self._int_from_money(finance_values[7].find_all('td')[3].div.get_text()) + finances.income_loan = self._int_from_money(finance_values[8].find_all('td')[3].div.get_text()) + finances.income_transfer = self._int_from_money(finance_values[9].find_all('td')[3].div.get_text()) + finances.income_visitors_friendlies = self._int_from_money(finance_values[10].find_all('td')[3].div.get_text()) + finances.income_friendlies = self._int_from_money(finance_values[11].find_all('td')[3].div.get_text()) + finances.income_funcup = self._int_from_money(finance_values[12].find_all('td')[3].div.get_text()) + finances.income_betting = self._int_from_money(finance_values[13].find_all('td')[3].div.get_text()) + + finances.expenses_player_salaries = self._int_from_money(finance_values[4].find_all('td')[11].div.get_text()) + finances.expenses_stadium = self._int_from_money(finance_values[5].find_all('td')[11].div.get_text()) + finances.expenses_youth = self._int_from_money(finance_values[6].find_all('td')[11].div.get_text()) + finances.expenses_interests = self._int_from_money(finance_values[7].find_all('td')[11].div.get_text()) + finances.expenses_trainings = self._int_from_money(finance_values[8].find_all('td')[11].div.get_text()) + finances.expenses_transfer = self._int_from_money(finance_values[9].find_all('td')[11].div.get_text()) + finances.expenses_compensation = self._int_from_money(finance_values[10].find_all('td')[11].div.get_text()) + finances.expenses_friendlies = self._int_from_money(finance_values[11].find_all('td')[11].div.get_text()) + finances.expenses_funcup = self._int_from_money(finance_values[12].find_all('td')[11].div.get_text()) + finances.expenses_betting = self._int_from_money(finance_values[13].find_all('td')[11].div.get_text()) finances.save() diff --git a/core/parsers/future_match_row_parser.py b/core/parsers/future_match_row_parser.py index 06baf71..6029c9b 100644 --- a/core/parsers/future_match_row_parser.py +++ b/core/parsers/future_match_row_parser.py @@ -25,9 +25,10 @@ def parse_html(self, row): """ # we assume to have parsed the season beforehand (with the matchday) - season = Matchday.objects.all()[0].season - matchday_number = row.find_all('td')[0].get_text().replace('\n', '') - matchday, _ = Matchday.objects.get_or_create(season=season, number=matchday_number) + matchday, _ = Matchday.objects.get_or_create( + season=Matchday.objects.all()[0].season, + number=row.find_all('td')[0].get_text().replace('\n', '') + ) is_home_match = "black" in row.find_all('td')[1].a.get('class') diff --git a/core/parsers/players_parser.py b/core/parsers/players_parser.py index 6749b5b..944a7c3 100644 --- a/core/parsers/players_parser.py +++ b/core/parsers/players_parser.py @@ -41,7 +41,7 @@ def parse_row(self, player_row): displayed_country = player_values[8].get_text().replace('\n', '').replace('\t', '').strip(' ') country_name = ''.join([i for i in displayed_country if not i.isdigit()]) - country_choices = dict(Country._meta.get_field('country').choices) + country_choices = Country.get_choices() country_no = list(country_choices.keys())[list(country_choices.values()).index(country_name)] nationality, _ = Country.objects.get_or_create(country=country_no) From cb280ed5a040eba33b927c07a86b995124ac62a6 Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Sat, 10 Dec 2016 18:40:38 +0100 Subject: [PATCH 24/71] #99 don't use _meta from models --- core/tests/unit/parser/test_player_statistics_parser.py | 6 +++--- core/tests/unit/test_core_models.py | 2 ++ 2 files changed, 5 insertions(+), 3 deletions(-) diff --git a/core/tests/unit/parser/test_player_statistics_parser.py b/core/tests/unit/parser/test_player_statistics_parser.py index 3365c3d..65e6a98 100644 --- a/core/tests/unit/parser/test_player_statistics_parser.py +++ b/core/tests/unit/parser/test_player_statistics_parser.py @@ -16,9 +16,9 @@ def setUp(self): user = OFMUserFactory.create() season = SeasonFactory.create() - country_choices = dict(Country._meta.get_field('country').choices) - country_no_greece = list(country_choices.keys())[list(country_choices.values()).index('Griechenland')] - nationality_greece, _ = Country.objects.get_or_create(country=country_no_greece) + country_choices = Country.get_choices() + country_iso_greece = list(country_choices.keys())[list(country_choices.values()).index('Griechenland')] + nationality_greece, _ = Country.objects.get_or_create(country=country_iso_greece) self.player = Player.objects.create( id='159883060', diff --git a/core/tests/unit/test_core_models.py b/core/tests/unit/test_core_models.py index 9e11d4e..170305e 100644 --- a/core/tests/unit/test_core_models.py +++ b/core/tests/unit/test_core_models.py @@ -119,6 +119,7 @@ def test_create_finance(self): self.assertTrue(f.matchday is not None) self.assertEqual(f.balance, 1000) + self.assertEqual(f.income_visitors_league, 100) self.assertEqual(f.income_sponsoring, 0) self.assertEqual(f.income_cup, 0) @@ -129,6 +130,7 @@ def test_create_finance(self): self.assertEqual(f.income_friendlies, 0) self.assertEqual(f.income_funcup, 0) self.assertEqual(f.income_betting, 0) + self.assertEqual(f.expenses_player_salaries, 100) self.assertEqual(f.expenses_stadium, 0) self.assertEqual(f.expenses_youth, 0) From d2817e62d53f07f60e9b63040306a627b250734c Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Sat, 10 Dec 2016 18:41:51 +0100 Subject: [PATCH 25/71] #99 less local variables --- core/parsers/stadium_statistics_parser.py | 32 +++++++------------ .../won_by_default_match_row_parser.py | 7 ++-- 2 files changed, 16 insertions(+), 23 deletions(-) diff --git a/core/parsers/stadium_statistics_parser.py b/core/parsers/stadium_statistics_parser.py index 16d6f64..180137a 100644 --- a/core/parsers/stadium_statistics_parser.py +++ b/core/parsers/stadium_statistics_parser.py @@ -41,31 +41,22 @@ def parse_html(self, soup): security_row = stadium_items[2] parking_row = stadium_items[3] - is_light_under_construction = \ - light_row.find_all('td')[1].img is not None and 'underconst' in light_row.find_all('td')[1].img['src'] - is_screen_under_construction = \ - screen_row.find_all('td')[1].img is not None and 'underconst' in screen_row.find_all('td')[1].img['src'] - is_security_under_construction = \ - security_row.find_all('td')[1].img is not None and 'underconst' in security_row.find_all('td')[1].img['src'] - is_parking_under_construction = \ - parking_row.find_all('td')[1].img is not None and 'underconst' in parking_row.find_all('td')[1].img['src'] - - if is_light_under_construction and last_stadium_level: + if StadiumStatisticsParser._is_under_construction(light_row) and last_stadium_level: light = last_stadium_level.light else: light = self._create_stadium_level_item_from_row(light_row) - if is_screen_under_construction and last_stadium_level: + if StadiumStatisticsParser._is_under_construction(screen_row) and last_stadium_level: screen = last_stadium_level.screen else: screen = self._create_stadium_level_item_from_row(screen_row) - if is_security_under_construction and last_stadium_level: + if StadiumStatisticsParser._is_under_construction(security_row) and last_stadium_level: security = last_stadium_level.security else: security = self._create_stadium_level_item_from_row(security_row) - if is_parking_under_construction and last_stadium_level: + if StadiumStatisticsParser._is_under_construction(parking_row) and last_stadium_level: parking = last_stadium_level.parking else: parking = self._create_stadium_level_item_from_row(parking_row) @@ -84,15 +75,16 @@ def parse_html(self, soup): return match_stadium_stat - def _create_stadium_level_item_from_row(self, row): - level = row.find_all('td')[2].span.get_text() - value = self.strip_euro_sign(row.find_all('td')[4].span.get_text().replace('.', '').strip()) - daily_costs = self.strip_euro_sign(row.find_all('td')[5].span.get_text().replace('.', '').strip()) + @staticmethod + def _is_under_construction(stadium_attribute): + return stadium_attribute.find_all('td')[1].img is not None and \ + 'underconst' in stadium_attribute.find_all('td')[1].img['src'] + def _create_stadium_level_item_from_row(self, row): stadium_level_item, _ = StadiumLevelItem.objects.get_or_create( - current_level=level, - value=value, - daily_costs=daily_costs + current_level=row.find_all('td')[2].span.get_text(), + value=self.strip_euro_sign(row.find_all('td')[4].span.get_text().replace('.', '').strip()), + daily_costs=self.strip_euro_sign(row.find_all('td')[5].span.get_text().replace('.', '').strip()) ) return stadium_level_item diff --git a/core/parsers/won_by_default_match_row_parser.py b/core/parsers/won_by_default_match_row_parser.py index d6651a5..2a07e63 100644 --- a/core/parsers/won_by_default_match_row_parser.py +++ b/core/parsers/won_by_default_match_row_parser.py @@ -25,9 +25,10 @@ def parse_html(self, row): """ # we assume to have parsed the season beforehand (with the matchday) - season = Matchday.objects.all()[0].season - matchday_number = row.find_all('td')[0].get_text().replace('\n', '') - matchday, _ = Matchday.objects.get_or_create(season=season, number=matchday_number) + matchday, _ = Matchday.objects.get_or_create( + season=Matchday.objects.all()[0].season, + number=row.find_all('td')[0].get_text().replace('\n', '') + ) is_home_match = "black" in row.find_all('td')[1].a.get('class') From d1d837836dfca00623619a172ad6b914b10d9d07 Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Sat, 10 Dec 2016 18:42:23 +0100 Subject: [PATCH 26/71] #99 don't use instance variables, if not needed --- .../views/test_ofm_stadium_detail_view.py | 20 +++++++++---------- .../test_ofm_stadium_stand_statistics_view.py | 18 ++++++++--------- .../views/test_ofm_stadium_statistics_view.py | 16 +++++++-------- 3 files changed, 27 insertions(+), 27 deletions(-) diff --git a/core/tests/unit/views/test_ofm_stadium_detail_view.py b/core/tests/unit/views/test_ofm_stadium_detail_view.py index 0f09069..ce52117 100644 --- a/core/tests/unit/views/test_ofm_stadium_detail_view.py +++ b/core/tests/unit/views/test_ofm_stadium_detail_view.py @@ -7,28 +7,28 @@ class OFMStadiumDetailsViewTestCase(TestCase): def setUp(self): - self.matchday = MatchdayFactory.create() - self.second_matchday = MatchdayFactory.create(number=1) - self.user1 = OFMUser.objects.create_user( + MatchdayFactory.create() + MatchdayFactory.create(number=1) + user1 = OFMUser.objects.create_user( username='alice', email='alice@ofmhelper.com', password='alice', ofm_username='alice', ofm_password='alice' ) - self.user2 = OFMUser.objects.create_user( + OFMUser.objects.create_user( username='bob', email='bob@ofmhelper.com', password='bob', ofm_username='bob', ofm_password='bob' ) - self.match = MatchFactory.create(user=self.user1) - self.stadium_stat = MatchStadiumStatisticsFactory.create(match=self.match) - self.north_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='N') - self.south_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='S') - self.west_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='W') - self.east_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='O') + match = MatchFactory.create(user=user1) + self.stadium_stat = MatchStadiumStatisticsFactory.create(match=match) + StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='N') + StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='S') + StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='W') + StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='O') self.client.login(username='alice', password='alice') def test_user_can_see_his_data(self): diff --git a/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py b/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py index ccd70bc..7a899fb 100644 --- a/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py +++ b/core/tests/unit/views/test_ofm_stadium_stand_statistics_view.py @@ -10,27 +10,27 @@ class OFMStadiumStandStatisticsViewTestCase(TestCase): def setUp(self): - self.matchday = MatchdayFactory.create() - self.user1 = OFMUser.objects.create_user( + MatchdayFactory.create() + user1 = OFMUser.objects.create_user( username='alice', email='alice@ofmhelper.com', password='alice', ofm_username='alice', ofm_password='alice' ) - self.user2 = OFMUser.objects.create_user( + OFMUser.objects.create_user( username='bob', email='bob@ofmhelper.com', password='bob', ofm_username='bob', ofm_password='bob' ) - self.match = MatchFactory.create(user=self.user1) - self.stadium_stat = MatchStadiumStatisticsFactory.create(match=self.match) - self.north_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='N') - self.south_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='S') - self.west_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='W') - self.east_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='O') + match = MatchFactory.create(user=user1) + stadium_stat = MatchStadiumStatisticsFactory.create(match=match) + StadiumStandStatisticsFactory.create(stadium_statistics=stadium_stat, sector='N') + StadiumStandStatisticsFactory.create(stadium_statistics=stadium_stat, sector='S') + StadiumStandStatisticsFactory.create(stadium_statistics=stadium_stat, sector='W') + StadiumStandStatisticsFactory.create(stadium_statistics=stadium_stat, sector='O') self.client.login(username='alice', password='alice') def test_user_can_see_his_data(self): diff --git a/core/tests/unit/views/test_ofm_stadium_statistics_view.py b/core/tests/unit/views/test_ofm_stadium_statistics_view.py index 2ee1df2..c24edf8 100644 --- a/core/tests/unit/views/test_ofm_stadium_statistics_view.py +++ b/core/tests/unit/views/test_ofm_stadium_statistics_view.py @@ -18,10 +18,10 @@ def setUp(self): self.match = MatchFactory.create(user=self.user) self.stadium_stat = MatchStadiumStatisticsFactory.create(match=self.match) - self.north_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='N') - self.south_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='S') - self.west_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='W') - self.east_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='O') + StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='N') + StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='S') + StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='W') + StadiumStandStatisticsFactory.create(stadium_statistics=self.stadium_stat, sector='O') def test_user_can_see_table(self): response = self.client.get(reverse('core:ofm:stadium_statistics_overview')) @@ -154,10 +154,10 @@ def test_user_can_filter_for_stadium_configuration(self): light_level = StadiumLevelItemFactory(current_level=1) level = StadiumLevelFactory.create(light=light_level) stadium_stat_2 = MatchStadiumStatisticsFactory.create(match=match2, level=level) - self.north_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=stadium_stat_2, sector='N') - self.south_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=stadium_stat_2, sector='S') - self.west_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=stadium_stat_2, sector='W') - self.east_stand_stat = StadiumStandStatisticsFactory.create(stadium_statistics=stadium_stat_2, sector='O') + StadiumStandStatisticsFactory.create(stadium_statistics=stadium_stat_2, sector='N') + StadiumStandStatisticsFactory.create(stadium_statistics=stadium_stat_2, sector='S') + StadiumStandStatisticsFactory.create(stadium_statistics=stadium_stat_2, sector='W') + StadiumStandStatisticsFactory.create(stadium_statistics=stadium_stat_2, sector='O') options = { 'harmonic_strength': 50, From 5d71550892f3343841d0f83404689ead5546f2bd Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Sat, 10 Dec 2016 19:51:25 +0100 Subject: [PATCH 27/71] #99 fixed some staticmethods --- core/managers/parser_manager.py | 9 ++++-- core/ofm_views.py | 34 ++++++++++------------- core/parsers/base_parser.py | 6 ++-- core/parsers/player_statistics_parser.py | 6 ++-- core/parsers/stadium_statistics_parser.py | 15 +++++----- core/views.py | 3 +- 6 files changed, 37 insertions(+), 36 deletions(-) diff --git a/core/managers/parser_manager.py b/core/managers/parser_manager.py index 44ecd1f..a67947d 100644 --- a/core/managers/parser_manager.py +++ b/core/managers/parser_manager.py @@ -33,12 +33,14 @@ def reset_parsing_flags(self): self.parsed_matchday = None self.players_already_parsed = False - def parse_ofm_version(self, site_manager): + @staticmethod + def parse_ofm_version(site_manager): site_manager.jump_to_frame(Constants.GitHub.LATEST_RELEASE) version_parser = OfmHelperVersionParser(site_manager.browser.page_source) return version_parser.parse() - def parse_matchday(self, request, site_manager): + @staticmethod + def parse_matchday(request, site_manager): site_manager.jump_to_frame(Constants.HEAD) matchday_parser = MatchdayParser(site_manager.browser.page_source) return matchday_parser.parse() @@ -108,7 +110,8 @@ def _parse_single_match(self, request, site_manager, row): else: return WonByDefaultMatchRowParser(row, request.user).parse() - def _parse_stadium_statistics(self, request, site_manager, match): + @staticmethod + def _parse_stadium_statistics(request, site_manager, match): site_manager.jump_to_frame(Constants.Stadium.ENVIRONMENT) stadium_statistics_parser = StadiumStatisticsParser(site_manager.browser.page_source, request.user, match) stadium_statistics_parser.parse() diff --git a/core/ofm_views.py b/core/ofm_views.py index 1ffc8f1..aa8d17b 100644 --- a/core/ofm_views.py +++ b/core/ofm_views.py @@ -39,9 +39,8 @@ def get(self, request, *args, **kwargs): contracts = Contract.objects.filter(user=self.request.user, sold_on_matchday=None) players = [contract.player for contract in contracts] current_matchday = Matchday.objects.all()[0] - current_season = current_matchday.season - newer_matchday_season = self.request.GET.get('newer_matchday_season', default=current_season.number) + newer_matchday_season = self.request.GET.get('newer_matchday_season', default=current_matchday.season.number) newer_matchday = self.request.GET.get('newer_matchday', default=current_matchday.number) older_matchday_season = self.request.GET.get('older_matchday_season') older_matchday = self.request.GET.get('older_matchday') @@ -60,11 +59,12 @@ def get(self, request, *args, **kwargs): player_statistics_json = [ self._get_player_statistics_diff_in_json(newer_player_statistics, older_player_statistics) for (newer_player_statistics, older_player_statistics) in player_statistics_tuples - ] + ] return self.render_json_response(player_statistics_json) - def _get_statistics_from_player_and_matchday(self, player, + @staticmethod + def _get_statistics_from_player_and_matchday(player, newer_matchday_season, newer_matchday, older_matchday_season, older_matchday): @@ -90,7 +90,8 @@ def _get_statistics_from_player_and_matchday(self, player, return newer_player_statistics, older_player_statistics - def _get_player_statistics_diff_in_json(self, newer_player_statistics, older_player_statistics): + @staticmethod + def _get_player_statistics_diff_in_json(newer_player_statistics, older_player_statistics): """ Args: newer_player_statistics: newer statistic @@ -245,12 +246,9 @@ def get(self, request, *args, **kwargs): return self.render_json_response(finances_json) - def _get_finances_diff_in_json(self, newer_finances, older_finances): + @staticmethod + def _get_finances_diff_in_json(newer_finances, older_finances): """ - Args: - newer_finances: newer finances - older_finances: older finances - Returns: A dictionary of finance data. If older_finances is None newer_finances is returned """ @@ -430,7 +428,7 @@ def get(self, request, *args, **kwargs): income_betting.append(data_source[0].income_betting) matchdays.append(data_source[0].matchday.number) - for idx, entry in enumerate(data_source): + for idx, _ in enumerate(data_source): if idx + 1 < data_source.count(): income_visitors_league.append( data_source[idx + 1].income_visitors_league - data_source[idx].income_visitors_league) @@ -508,7 +506,7 @@ def get(self, request, *args, **kwargs): expenses_betting.append(-data_source[0].expenses_betting) matchdays.append(data_source[0].matchday.number) - for idx, entry in enumerate(data_source): + for idx, _ in enumerate(data_source): if idx + 1 < data_source.count(): expenses_player_salaries.append( data_source[idx].expenses_player_salaries - data_source[idx + 1].expenses_player_salaries) @@ -580,11 +578,9 @@ def get(self, request, *args, **kwargs): return self.render_json_response(match_json) - def _get_match_in_json(self, match): + @staticmethod + def _get_match_in_json(match): """ - Args: - match: Match - Returns: A dictionary of match data. """ @@ -746,11 +742,9 @@ def get(self, request, *args, **kwargs): return self.render_json_response(stadium_statistics_json) - def _get_stadium_statistics_in_json(self, stadium_stat): + @staticmethod + def _get_stadium_statistics_in_json(stadium_stat): """ - Args: - stadium_stat: MatchStadiumStatistics - Returns: A dictionary of stadium statistics data. """ diff --git a/core/parsers/base_parser.py b/core/parsers/base_parser.py index 59eb125..85c0298 100644 --- a/core/parsers/base_parser.py +++ b/core/parsers/base_parser.py @@ -11,12 +11,14 @@ def __init__(self): def parse(self): raise NotImplementedError("Should have implemented this") - def _filter_invalid_cells(self, table_cells): + @staticmethod + def _filter_invalid_cells(table_cells): import re counter_cell_pattern = re.compile(r'[0-9]+') return [cell for cell in table_cells if str(cell).replace(' ', '').replace('\t', '').replace('\n', '') != '??' and not counter_cell_pattern.match(str(cell))] - def strip_euro_sign(self, money): + @staticmethod + def strip_euro_sign(money): return money[:-2] diff --git a/core/parsers/player_statistics_parser.py b/core/parsers/player_statistics_parser.py index 0155f3d..68c4496 100644 --- a/core/parsers/player_statistics_parser.py +++ b/core/parsers/player_statistics_parser.py @@ -104,10 +104,12 @@ def _create_contract(self, player): ) return contract - def _get_value_from_multivalue_table_cell(self, field, index): + @staticmethod + def _get_value_from_multivalue_table_cell(field, index): return field.get_text().split(MULTIVALUE_SEPARATOR)[index].strip() - def _get_ep_tp_value_from_table_cell(self, field): + @staticmethod + def _get_ep_tp_value_from_table_cell(field): return field.get_text().strip('\n').split('\n')[0].strip('\n').strip('\t').replace('.', '') def _get_equity_value_from_table_cell(self, field): diff --git a/core/parsers/stadium_statistics_parser.py b/core/parsers/stadium_statistics_parser.py index 180137a..9fe5155 100644 --- a/core/parsers/stadium_statistics_parser.py +++ b/core/parsers/stadium_statistics_parser.py @@ -41,22 +41,22 @@ def parse_html(self, soup): security_row = stadium_items[2] parking_row = stadium_items[3] - if StadiumStatisticsParser._is_under_construction(light_row) and last_stadium_level: + if self._is_under_construction(light_row) and last_stadium_level: light = last_stadium_level.light else: light = self._create_stadium_level_item_from_row(light_row) - if StadiumStatisticsParser._is_under_construction(screen_row) and last_stadium_level: + if self._is_under_construction(screen_row) and last_stadium_level: screen = last_stadium_level.screen else: screen = self._create_stadium_level_item_from_row(screen_row) - if StadiumStatisticsParser._is_under_construction(security_row) and last_stadium_level: + if self._is_under_construction(security_row) and last_stadium_level: security = last_stadium_level.security else: security = self._create_stadium_level_item_from_row(security_row) - if StadiumStatisticsParser._is_under_construction(parking_row) and last_stadium_level: + if self._is_under_construction(parking_row) and last_stadium_level: parking = last_stadium_level.parking else: parking = self._create_stadium_level_item_from_row(parking_row) @@ -80,11 +80,12 @@ def _is_under_construction(stadium_attribute): return stadium_attribute.find_all('td')[1].img is not None and \ 'underconst' in stadium_attribute.find_all('td')[1].img['src'] - def _create_stadium_level_item_from_row(self, row): + @staticmethod + def _create_stadium_level_item_from_row(row): stadium_level_item, _ = StadiumLevelItem.objects.get_or_create( current_level=row.find_all('td')[2].span.get_text(), - value=self.strip_euro_sign(row.find_all('td')[4].span.get_text().replace('.', '').strip()), - daily_costs=self.strip_euro_sign(row.find_all('td')[5].span.get_text().replace('.', '').strip()) + value=BaseParser.strip_euro_sign(row.find_all('td')[4].span.get_text().replace('.', '').strip()), + daily_costs=BaseParser.strip_euro_sign(row.find_all('td')[5].span.get_text().replace('.', '').strip()) ) return stadium_level_item diff --git a/core/views.py b/core/views.py index a716f05..c6e1adc 100644 --- a/core/views.py +++ b/core/views.py @@ -160,11 +160,10 @@ def get(self, request, *args, **kwargs): class GetChecklistItemsForTodayView(CsrfExemptMixin, JsonRequestResponseMixin, View): def get(self, request, *args, **kwargs): current_matchday = Matchday.get_current() - next_matchday_number = current_matchday.number + 1 home_match_tomorrow = Match.objects.filter( user=request.user, matchday__season__number=current_matchday.season.number, - matchday__number=next_matchday_number, + matchday__number=current_matchday.number + 1, is_home_match=True ) checklist_items = ChecklistItem.objects.filter(checklist__user=request.user) From 6ca14d303948efe43376e6e937a81581efb04f71 Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Sat, 10 Dec 2016 21:04:13 +0100 Subject: [PATCH 28/71] #99 split out ofm views into new package --- core/ofm_urls.py | 10 +- core/ofm_views.py | 911 -------------------------- core/rename_me_views/__init__.py | 0 core/rename_me_views/finance_views.py | 354 ++++++++++ core/rename_me_views/match_views.py | 113 ++++ core/rename_me_views/player_views.py | 196 ++++++ core/rename_me_views/stadium_views.py | 264 ++++++++ core/rename_me_views/view_utils.py | 9 + core/urls.py | 1 + 9 files changed, 943 insertions(+), 915 deletions(-) delete mode 100644 core/ofm_views.py create mode 100644 core/rename_me_views/__init__.py create mode 100644 core/rename_me_views/finance_views.py create mode 100644 core/rename_me_views/match_views.py create mode 100644 core/rename_me_views/player_views.py create mode 100644 core/rename_me_views/stadium_views.py create mode 100644 core/rename_me_views/view_utils.py diff --git a/core/ofm_urls.py b/core/ofm_urls.py index a7f9832..979d88a 100644 --- a/core/ofm_urls.py +++ b/core/ofm_urls.py @@ -1,9 +1,11 @@ from django.conf.urls import url -from core.ofm_views import PlayerDetailView, PlayerStatisticsView, PlayerStatisticsAsJsonView, FinanceDataView, \ - FinancesAsJsonView, MatchesView, MatchesAsJsonView, StadiumStatisticsView, StadiumStatisticsAsJsonView, \ - StadiumDetailView, StadiumStandStatisticsView, FinanceIncomeChartView, FinanceExpensesChartView, \ - FinanceBalanceChartView, PlayerChartView, MatchesSummaryJsonView, StadiumStandStatisticsChartView +from core.rename_me_views.stadium_views import StadiumStatisticsView, StadiumStatisticsAsJsonView, StadiumDetailView, \ + StadiumStandStatisticsView, StadiumStandStatisticsChartView +from core.rename_me_views.match_views import MatchesView, MatchesAsJsonView, MatchesSummaryJsonView +from core.rename_me_views.finance_views import FinanceDataView, FinancesAsJsonView, FinanceBalanceChartView, \ + FinanceIncomeChartView, FinanceExpensesChartView +from core.rename_me_views.player_views import PlayerStatisticsView, PlayerStatisticsAsJsonView, PlayerDetailView, PlayerChartView app_name = 'ofm' urlpatterns = [ diff --git a/core/ofm_views.py b/core/ofm_views.py deleted file mode 100644 index aa8d17b..0000000 --- a/core/ofm_views.py +++ /dev/null @@ -1,911 +0,0 @@ -import ast -import locale - -from braces.views import CsrfExemptMixin, JsonRequestResponseMixin -from django.contrib.auth.decorators import login_required -from django.core.exceptions import MultipleObjectsReturned -from django.utils.decorators import method_decorator -from django.views.generic import DetailView, TemplateView, View - -from core.models import Player, Contract, PlayerStatistics, Finance, Matchday, Match, MatchStadiumStatistics, \ - StadiumStandStatistics, AwpBoundaries - - -def _validate_filtered_field(field): - if len(field) > 1: - raise MultipleObjectsReturned - elif field: - field = field[0] - return field - - -@method_decorator(login_required, name='dispatch') -class PlayerStatisticsView(TemplateView): - template_name = 'core/ofm/player_statistics.html' - - def get_context_data(self, **kwargs): - matchdays = Matchday.objects.filter(player_statistics__isnull=False).distinct() - - context = super(PlayerStatisticsView, self).get_context_data(**kwargs) - context['matchdays'] = matchdays - context['players_count'] = Contract.objects.filter(user=self.request.user, sold_on_matchday=None).count() - - return context - - -@method_decorator(login_required, name='dispatch') -class PlayerStatisticsAsJsonView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): - contracts = Contract.objects.filter(user=self.request.user, sold_on_matchday=None) - players = [contract.player for contract in contracts] - current_matchday = Matchday.objects.all()[0] - - newer_matchday_season = self.request.GET.get('newer_matchday_season', default=current_matchday.season.number) - newer_matchday = self.request.GET.get('newer_matchday', default=current_matchday.number) - older_matchday_season = self.request.GET.get('older_matchday_season') - older_matchday = self.request.GET.get('older_matchday') - diff_mode_enabled = older_matchday and older_matchday_season - - player_statistics_tuples = [] - for player in players: - newer_player_statistics, older_player_statistics = self._get_statistics_from_player_and_matchday( - player, - newer_matchday_season, newer_matchday, - older_matchday_season, older_matchday - ) - if newer_player_statistics and (older_player_statistics or not diff_mode_enabled): - player_statistics_tuples.append((newer_player_statistics, older_player_statistics)) - - player_statistics_json = [ - self._get_player_statistics_diff_in_json(newer_player_statistics, older_player_statistics) - for (newer_player_statistics, older_player_statistics) in player_statistics_tuples - ] - - return self.render_json_response(player_statistics_json) - - @staticmethod - def _get_statistics_from_player_and_matchday(player, - newer_matchday_season, newer_matchday, - older_matchday_season, older_matchday): - - newer_player_statistics = PlayerStatistics.objects.filter( - player=player, - matchday__season__number=newer_matchday_season, - matchday__number=newer_matchday - ) - older_player_statistics = PlayerStatistics.objects.filter( - player=player, - matchday__season__number=older_matchday_season, - matchday__number=older_matchday - ) - - newer_player_statistics = _validate_filtered_field(newer_player_statistics) - older_player_statistics = _validate_filtered_field(older_player_statistics) - - if not newer_player_statistics: - newer_player_statistics = PlayerStatistics.objects.filter( - player=player, - matchday__season__number=newer_matchday_season - ).order_by('matchday')[0] - - return newer_player_statistics, older_player_statistics - - @staticmethod - def _get_player_statistics_diff_in_json(newer_player_statistics, older_player_statistics): - """ - Args: - newer_player_statistics: newer statistic - older_player_statistics: older statistic - - Returns: - A dictionary of player statistics data. If st2 is None st1 is returned - """ - - strength = newer_player_statistics.strength - if older_player_statistics: - strength = newer_player_statistics.strength - older_player_statistics.strength - ep = newer_player_statistics.ep - if older_player_statistics: - ep = newer_player_statistics.ep - older_player_statistics.ep - tp = newer_player_statistics.tp - if older_player_statistics: - tp = newer_player_statistics.tp - older_player_statistics.tp - awp = newer_player_statistics.awp - if older_player_statistics: - awp = newer_player_statistics.awp - older_player_statistics.awp - freshness = newer_player_statistics.freshness - if older_player_statistics: - freshness = newer_player_statistics.freshness - older_player_statistics.freshness - - awp_boundaries = AwpBoundaries.get_from_matchday(newer_player_statistics.matchday) - awp_to_next_bound = awp_boundaries[newer_player_statistics.strength + 1] - newer_player_statistics.awp - - statistic_diff = dict() - statistic_diff['position'] = newer_player_statistics.player.position - statistic_diff['age'] = newer_player_statistics.age - statistic_diff['strength'] = strength - statistic_diff['name'] = '%s' % (newer_player_statistics.player.get_absolute_url(), - newer_player_statistics.player.name) - statistic_diff['ep'] = ep - statistic_diff['tp'] = tp - statistic_diff['awp'] = awp - statistic_diff['freshness'] = freshness - statistic_diff['games_in_season'] = newer_player_statistics.games_in_season - statistic_diff['goals_in_season'] = newer_player_statistics.goals_in_season - statistic_diff['won_tacklings_in_season'] = newer_player_statistics.won_tacklings_in_season - statistic_diff['lost_tacklings_in_season'] = newer_player_statistics.lost_tacklings_in_season - statistic_diff['won_friendly_tacklings_in_season'] = newer_player_statistics.won_friendly_tacklings_in_season - statistic_diff['lost_friendly_tacklings_in_season'] = newer_player_statistics.lost_friendly_tacklings_in_season - statistic_diff['yellow_cards_in_season'] = newer_player_statistics.yellow_cards_in_season - statistic_diff['red_cards_in_season'] = newer_player_statistics.red_cards_in_season - statistic_diff['equity'] = newer_player_statistics.equity - statistic_diff['awp_to_next_bound'] = awp_to_next_bound - - return statistic_diff - - -@method_decorator(login_required, name='dispatch') -class PlayerDetailView(DetailView): - context_object_name = 'player' - template_name = 'core/ofm/player_detail.html' - queryset = Player.objects.all() - - def get_context_data(self, **kwargs): - context = super(PlayerDetailView, self).get_context_data(**kwargs) - - player = self.get_object() - current_season = Matchday.objects.all()[0].season - seasons = [] - player_stats = PlayerStatistics.objects.filter(player=player).order_by('matchday') - for player_stat in player_stats: - if player_stat.matchday.season not in seasons: - seasons.append(player_stat.matchday.season) - - context['seasons'] = seasons - if player: - context['player_age'] = current_season.number - player.birth_season.number - context['player_strength'] = player_stats[0].strength - - return context - - def get_object(self, **kwargs): - player = super(PlayerDetailView, self).get_object() - contracts = Contract.objects.filter(user=self.request.user, player=player, sold_on_matchday=None) - return player if contracts.count() > 0 else None - - -@method_decorator(login_required, name='dispatch') -class PlayerChartView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): - current_season_number = Matchday.objects.all()[0].season.number - season_number = self.request.GET.get('season_number', default=current_season_number) - player_id = self.request.GET.get('player_id') - player = Player.objects.filter(id=player_id) - player_statistics = PlayerStatistics.objects.filter(player=player, matchday__season__number=season_number) - awps = [player_stat.awp for player_stat in player_statistics] - - chart_json = { - "series": [{ - "name": 'AWP', - "data": awps - }], - "categories": [player_stat.matchday.number for player_stat in player_statistics] - } - - matchdays = [p.matchday for p in player_statistics] - current_player_statistics = PlayerStatistics.objects.filter(player=player).order_by('matchday')[0] - - current_awp_boundaries = AwpBoundaries.get_from_matchday(current_player_statistics.matchday) - - for strength in current_awp_boundaries: - if current_awp_boundaries[strength] >= min(awps) and strength > current_player_statistics.strength: - awp_boundary_values = [AwpBoundaries.get_from_matchday(matchday)[strength] for matchday in matchdays] - chart_json['series'].append({'name': 'AWP-Grenze: %s' % strength, 'data': awp_boundary_values}) - if current_awp_boundaries[strength] >= max(awps): - break - - return self.render_json_response(chart_json) - - -@method_decorator(login_required, name='dispatch') -class FinanceDataView(TemplateView): - template_name = 'core/ofm/finances.html' - - def get_context_data(self, **kwargs): - context = super(FinanceDataView, self).get_context_data(**kwargs) - matchdays = Matchday.objects.filter(finance__isnull=False).distinct() - context['matchdays'] = matchdays - - return context - - -@method_decorator(login_required, name='dispatch') -class FinancesAsJsonView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): - newer_matchday_season = self.request.GET.get('newer_matchday_season', - default=Matchday.objects.all()[0].season.number) - newer_matchday = self.request.GET.get('newer_matchday', default=Matchday.objects.all()[0].number) - older_matchday_season = self.request.GET.get('older_matchday_season') - older_matchday = self.request.GET.get('older_matchday') - - newer_finances = Finance.objects.filter( - user=request.user, - matchday__season__number=newer_matchday_season, - matchday__number=newer_matchday - ) - older_finances = Finance.objects.filter( - user=request.user, - matchday__season__number=older_matchday_season, - matchday__number=older_matchday - ) - - newer_finances = _validate_filtered_field(newer_finances) - older_finances = _validate_filtered_field(older_finances) - - finances_json = self._get_finances_diff_in_json(newer_finances, older_finances) - - return self.render_json_response(finances_json) - - @staticmethod - def _get_finances_diff_in_json(newer_finances, older_finances): - """ - Returns: - A dictionary of finance data. If older_finances is None newer_finances is returned - """ - - if not newer_finances: - newer_finances = Finance.objects.all().order_by('matchday')[0] - - account_balance = newer_finances.balance - - income_visitors_league = newer_finances.income_visitors_league - if older_finances: - income_visitors_league = newer_finances.income_visitors_league - older_finances.income_visitors_league - - income_sponsoring = newer_finances.income_sponsoring - if older_finances: - income_sponsoring = newer_finances.income_sponsoring - older_finances.income_sponsoring - - income_cup = newer_finances.income_cup - if older_finances: - income_cup = newer_finances.income_cup - older_finances.income_cup - - income_interests = newer_finances.income_interests - if older_finances: - income_interests = newer_finances.income_interests - older_finances.income_interests - - income_loan = newer_finances.income_loan - if older_finances: - income_loan = newer_finances.income_loan - older_finances.income_loan - - income_transfer = newer_finances.income_transfer - if older_finances: - income_transfer = newer_finances.income_transfer - older_finances.income_transfer - - income_visitors_friendlies = newer_finances.income_visitors_friendlies - if older_finances: - income_visitors_friendlies = newer_finances.income_visitors_friendlies - \ - older_finances.income_visitors_friendlies - - income_friendlies = newer_finances.income_friendlies - if older_finances: - income_friendlies = newer_finances.income_friendlies - older_finances.income_friendlies - - income_funcup = newer_finances.income_funcup - if older_finances: - income_funcup = newer_finances.income_funcup - older_finances.income_funcup - - income_betting = newer_finances.income_betting - if older_finances: - income_betting = newer_finances.income_betting - older_finances.income_betting - - expenses_player_salaries = -newer_finances.expenses_player_salaries - if older_finances: - expenses_player_salaries = -( - newer_finances.expenses_player_salaries - older_finances.expenses_player_salaries) - - expenses_stadium = -newer_finances.expenses_stadium - if older_finances: - expenses_stadium = -(newer_finances.expenses_stadium - older_finances.expenses_stadium) - - expenses_youth = -newer_finances.expenses_youth - if older_finances: - expenses_youth = -(newer_finances.expenses_youth - older_finances.expenses_youth) - - expenses_interests = -newer_finances.expenses_interests - if older_finances: - expenses_interests = -(newer_finances.expenses_interests - older_finances.expenses_interests) - - expenses_trainings = -newer_finances.expenses_trainings - if older_finances: - expenses_trainings = -(newer_finances.expenses_trainings - older_finances.expenses_trainings) - - expenses_transfer = -newer_finances.expenses_transfer - if older_finances: - expenses_transfer = -(newer_finances.expenses_transfer - older_finances.expenses_transfer) - - expenses_compensation = -newer_finances.expenses_compensation - if older_finances: - expenses_compensation = -(newer_finances.expenses_compensation - older_finances.expenses_compensation) - - expenses_friendlies = -newer_finances.expenses_friendlies - if older_finances: - expenses_friendlies = -(newer_finances.expenses_friendlies - older_finances.expenses_friendlies) - - expenses_funcup = -newer_finances.expenses_funcup - if older_finances: - expenses_funcup = -(newer_finances.expenses_funcup - older_finances.expenses_funcup) - - expenses_betting = -newer_finances.expenses_betting - if older_finances: - expenses_betting = -(newer_finances.expenses_betting - older_finances.expenses_betting) - - finances_diff = dict() - finances_diff['account_balance'] = account_balance - - finances_diff['income_visitors_league'] = income_visitors_league - finances_diff['income_sponsoring'] = income_sponsoring - finances_diff['income_cup'] = income_cup - finances_diff['income_interests'] = income_interests - finances_diff['income_loan'] = income_loan - finances_diff['income_transfer'] = income_transfer - finances_diff['income_visitors_friendlies'] = income_visitors_friendlies - finances_diff['income_friendlies'] = income_friendlies - finances_diff['income_funcup'] = income_funcup - finances_diff['income_betting'] = income_betting - - finances_diff['expenses_player_salaries'] = expenses_player_salaries - finances_diff['expenses_stadium'] = expenses_stadium - finances_diff['expenses_youth'] = expenses_youth - finances_diff['expenses_interests'] = expenses_interests - finances_diff['expenses_trainings'] = expenses_trainings - finances_diff['expenses_transfer'] = expenses_transfer - finances_diff['expenses_compensation'] = expenses_compensation - finances_diff['expenses_friendlies'] = expenses_friendlies - finances_diff['expenses_funcup'] = expenses_funcup - finances_diff['expenses_betting'] = expenses_betting - - sum_income = income_visitors_league + income_sponsoring + income_cup + income_interests + income_loan + \ - income_transfer + income_visitors_friendlies + income_friendlies + income_funcup + income_betting - sum_expenses = expenses_player_salaries + expenses_stadium + expenses_youth + expenses_interests + \ - expenses_trainings + expenses_transfer + expenses_compensation + expenses_friendlies + \ - expenses_funcup + expenses_betting - - finances_diff['sum_income'] = sum_income - finances_diff['sum_expenses'] = sum_expenses - finances_diff['balance'] = sum_income + sum_expenses - - return [finances_diff] - - -@method_decorator(login_required, name='dispatch') -class FinanceBalanceChartView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): - current_season_number = Matchday.objects.all()[0].season.number - season_number = self.request.GET.get('season_number', default=current_season_number) - data_source = Finance.objects.filter(user=self.request.user, matchday__season__number=season_number) - - chart_json = { - "series": [{ - "name": 'Kontostand', - "data": [finance.balance for finance in data_source] - }], - "categories": [finance.matchday.number for finance in data_source] - } - - return self.render_json_response(chart_json) - - -@method_decorator(login_required, name='dispatch') -class FinanceIncomeChartView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): - current_season_number = Matchday.objects.all()[0].season.number - season_number = self.request.GET.get('season_number', default=current_season_number) - data_source = Finance.objects.filter(user=self.request.user, matchday__season__number=season_number) - - income_visitors_league = [] - income_sponsoring = [] - income_cup = [] - income_interests = [] - income_loan = [] - income_transfer = [] - income_visitors_friendlies = [] - income_friendlies = [] - income_funcup = [] - income_betting = [] - matchdays = [] - - if len(data_source) >= 1: - income_visitors_league.append(data_source[0].income_visitors_league) - income_sponsoring.append(data_source[0].income_sponsoring) - income_cup.append(data_source[0].income_cup) - income_interests.append(data_source[0].income_interests) - income_loan.append(data_source[0].income_loan) - income_transfer.append(data_source[0].income_transfer) - income_visitors_friendlies.append(data_source[0].income_visitors_friendlies) - income_friendlies.append(data_source[0].income_friendlies) - income_funcup.append(data_source[0].income_funcup) - income_betting.append(data_source[0].income_betting) - matchdays.append(data_source[0].matchday.number) - - for idx, _ in enumerate(data_source): - if idx + 1 < data_source.count(): - income_visitors_league.append( - data_source[idx + 1].income_visitors_league - data_source[idx].income_visitors_league) - income_sponsoring.append(data_source[idx + 1].income_sponsoring - data_source[idx].income_sponsoring) - income_cup.append(data_source[idx + 1].income_cup - data_source[idx].income_cup) - income_interests.append(data_source[idx + 1].income_interests - data_source[idx].income_interests) - income_loan.append(data_source[idx + 1].income_loan - data_source[idx].income_loan) - income_transfer.append(data_source[idx + 1].income_transfer - data_source[idx].income_transfer) - income_visitors_friendlies.append( - data_source[idx + 1].income_visitors_friendlies - data_source[idx].income_visitors_friendlies) - income_friendlies.append(data_source[idx + 1].income_friendlies - data_source[idx].income_friendlies) - income_funcup.append(data_source[idx + 1].income_funcup - data_source[idx].income_funcup) - income_betting.append(data_source[idx + 1].income_betting - data_source[idx].income_betting) - matchdays.append(data_source[idx + 1].matchday.number) - - series = [] - if sum(income_visitors_league) is not 0: - series.append({"name": 'Ticketeinnahmen Liga', "data": income_visitors_league}) - if sum(income_sponsoring) is not 0: - series.append({"name": 'Sponsor', "data": income_sponsoring}) - if sum(income_cup) is not 0: - series.append({"name": 'Pokal', "data": income_cup}) - if sum(income_interests) is not 0: - series.append({"name": 'Zinsen', "data": income_interests}) - if sum(income_loan) is not 0: - series.append({"name": 'Kredite', "data": income_loan}) - if sum(income_transfer) is not 0: - series.append({"name": 'Spielertransfers', "data": income_transfer}) - if sum(income_visitors_friendlies) is not 0: - series.append({"name": 'Ticketeinnahmen Freundschaftsspiele', "data": income_visitors_friendlies}) - if sum(income_friendlies) is not 0: - series.append({"name": 'Freundschaftsspiele', "data": income_friendlies}) - if sum(income_funcup) is not 0: - series.append({"name": 'Fun-Cup', "data": income_funcup}) - if sum(income_betting) is not 0: - series.append({"name": 'Wetten', "data": income_betting}) - - chart_json = { - "series": series, - "categories": matchdays - } - - return self.render_json_response(chart_json) - - -@method_decorator(login_required, name='dispatch') -class FinanceExpensesChartView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): - current_season_number = Matchday.objects.all()[0].season.number - season_number = self.request.GET.get('season_number', default=current_season_number) - data_source = Finance.objects.filter(user=self.request.user, matchday__season__number=season_number) - - expenses_player_salaries = [] - expenses_stadium = [] - expenses_youth = [] - expenses_interests = [] - expenses_trainings = [] - expenses_transfer = [] - expenses_compensation = [] - expenses_friendlies = [] - expenses_funcup = [] - expenses_betting = [] - matchdays = [] - - if len(data_source) >= 1: - expenses_player_salaries.append(-data_source[0].expenses_player_salaries) - expenses_stadium.append(-data_source[0].expenses_stadium) - expenses_youth.append(-data_source[0].expenses_youth) - expenses_interests.append(-data_source[0].expenses_interests) - expenses_trainings.append(-data_source[0].expenses_trainings) - expenses_transfer.append(-data_source[0].expenses_transfer) - expenses_compensation.append(-data_source[0].expenses_compensation) - expenses_friendlies.append(-data_source[0].expenses_friendlies) - expenses_funcup.append(-data_source[0].expenses_funcup) - expenses_betting.append(-data_source[0].expenses_betting) - matchdays.append(data_source[0].matchday.number) - - for idx, _ in enumerate(data_source): - if idx + 1 < data_source.count(): - expenses_player_salaries.append( - data_source[idx].expenses_player_salaries - data_source[idx + 1].expenses_player_salaries) - expenses_stadium.append(data_source[idx].expenses_stadium - data_source[idx + 1].expenses_stadium) - expenses_youth.append(data_source[idx].expenses_youth - data_source[idx + 1].expenses_youth) - expenses_interests.append(data_source[idx].expenses_interests - data_source[idx + 1].expenses_interests) - expenses_trainings.append(data_source[idx].expenses_trainings - data_source[idx + 1].expenses_trainings) - expenses_transfer.append(data_source[idx].expenses_transfer - data_source[idx + 1].expenses_transfer) - expenses_compensation.append( - data_source[idx].expenses_compensation - data_source[idx + 1].expenses_compensation) - expenses_friendlies.append( - data_source[idx].expenses_friendlies - data_source[idx + 1].expenses_friendlies) - expenses_funcup.append(data_source[idx].expenses_funcup - data_source[idx + 1].expenses_funcup) - expenses_betting.append(data_source[idx].expenses_betting - data_source[idx + 1].expenses_betting) - matchdays.append(data_source[idx + 1].matchday.number) - - series = [] - if sum(expenses_player_salaries) is not 0: - series.append({"name": 'Spielergehalt', "data": expenses_player_salaries}) - if sum(expenses_stadium) is not 0: - series.append({"name": 'Stadion', "data": expenses_stadium}) - if sum(expenses_youth) is not 0: - series.append({"name": u'Jugendförderung', "data": expenses_youth}) - if sum(expenses_interests) is not 0: - series.append({"name": 'Zinsen', "data": expenses_interests}) - if sum(expenses_trainings) is not 0: - series.append({"name": 'Training', "data": expenses_trainings}) - if sum(expenses_transfer) is not 0: - series.append({"name": 'Spielertransfers', "data": expenses_transfer}) - if sum(expenses_compensation) is not 0: - series.append({"name": 'Abfindungen', "data": expenses_compensation}) - if sum(expenses_friendlies) is not 0: - series.append({"name": 'Freundschaftsspiele', "data": expenses_friendlies}) - if sum(expenses_funcup) is not 0: - series.append({"name": 'Fun-Cup', "data": expenses_funcup}) - if sum(expenses_betting) is not 0: - series.append({"name": 'Wetten', "data": expenses_betting}) - - chart_json = { - "series": series, - "categories": matchdays - } - - return self.render_json_response(chart_json) - - -@method_decorator(login_required, name='dispatch') -class MatchesView(TemplateView): - template_name = 'core/ofm/matches.html' - - def get_context_data(self, **kwargs): - context = super(MatchesView, self).get_context_data(**kwargs) - - matchdays = Matchday.objects.filter(matches__isnull=False).distinct() - seasons = set(m.season.number for m in matchdays) - - context['seasons'] = sorted(seasons, reverse=True) - - return context - - -@method_decorator(login_required, name='dispatch') -class MatchesAsJsonView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): - season = self.request.GET.get('season', default=Matchday.objects.all()[0].season.number) - matches = Match.objects.filter(user=self.request.user, matchday__season__number=season) - - match_json = [self._get_match_in_json(match) for match in matches] - - return self.render_json_response(match_json) - - @staticmethod - def _get_match_in_json(match): - """ - Returns: - A dictionary of match data. - """ - locale.setlocale(locale.LC_ALL, '') - - if match.is_home_match: - home_team_name = "" + match.home_team_statistics.team_name + "" - guest_team_name = match.guest_team_statistics.team_name - if hasattr(match, 'stadium_statistics'): - venue = "" + match.venue + "" - else: - venue = match.venue - else: - home_team_name = match.home_team_statistics.team_name - guest_team_name = "" + match.guest_team_statistics.team_name + "" - venue = match.venue - - result_score = str(match.home_team_statistics.score) + ":" + str(match.guest_team_statistics.score) - if match.is_in_future: - result = "-:-" - elif match.is_won: - result = "" + result_score + "" - elif match.is_draw: - result = "" + result_score + "" - else: - result = "" + result_score + "" - - match_stat = dict() - match_stat['home_team'] = home_team_name - match_stat['guest_team'] = guest_team_name - match_stat['result'] = result - home_strength = match.home_team_statistics.strength - if home_strength == int(home_strength): - match_stat['home_strength'] = int(home_strength) - else: - match_stat['home_strength'] = locale.format("%.1f", home_strength) - guest_strength = match.guest_team_statistics.strength - if guest_strength == int(guest_strength): - match_stat['guest_strength'] = int(guest_strength) - else: - match_stat['guest_strength'] = locale.format("%.1f", guest_strength) - match_stat['home_ball_possession'] = locale.format("%.1f", match.home_team_statistics.ball_possession) + " %" - match_stat['guest_ball_possession'] = locale.format("%.1f", match.guest_team_statistics.ball_possession) + " %" - match_stat['home_chances'] = match.home_team_statistics.chances - match_stat['guest_chances'] = match.guest_team_statistics.chances - match_stat['home_yellow_cards'] = match.home_team_statistics.yellow_cards - match_stat['guest_yellow_cards'] = match.guest_team_statistics.yellow_cards - match_stat['home_red_cards'] = match.home_team_statistics.red_cards - match_stat['guest_red_cards'] = match.guest_team_statistics.red_cards - match_stat['venue'] = venue - match_stat['matchday'] = match.matchday.number - - return match_stat - - -@method_decorator(login_required, name='dispatch') -class MatchesSummaryJsonView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): - current_season = Matchday.objects.all()[0].season - season_number = self.request.GET.get('season_number', current_season.number) - matches_won = len( - [match for match in Match.objects.filter(matchday__season__number=season_number) if match.is_won]) - matches_draw = len( - [match for match in Match.objects.filter(matchday__season__number=season_number) if match.is_draw]) - matches_lost = len( - [match for match in Match.objects.filter(matchday__season__number=season_number) if match.is_lost]) - - json = { - "matches_won": matches_won, - "matches_draw": matches_draw, - "matches_lost": matches_lost - } - - return self.render_json_response(json) - - -@method_decorator(login_required, name='dispatch') -class StadiumStatisticsView(TemplateView): - template_name = 'core/ofm/stadium_statistics.html' - - def get_context_data(self, **kwargs): - context = super(StadiumStatisticsView, self).get_context_data(**kwargs) - - matchdays = Matchday.objects.filter(matches__isnull=False).distinct() - seasons = set(m.season.number for m in matchdays) - - tolerance = 5 - if self.request.COOKIES.get('slider_min') and \ - self.request.COOKIES.get('slider_max') and \ - self.request.COOKIES.get('tolerance'): - slider_min = self.request.COOKIES['slider_min'] - slider_max = self.request.COOKIES['slider_max'] - tolerance = self.request.COOKIES['tolerance'] - elif Match.objects.count() > 0: - # latest home match - match = Match.objects.filter(user=self.request.user, is_home_match=True).order_by('matchday')[0] - slider_min = int(min(match.home_team_statistics.strength, match.guest_team_statistics.strength)) - slider_max = int(max(match.home_team_statistics.strength, match.guest_team_statistics.strength)) - else: - slider_min = 100 - slider_max = 150 - - unique_stadium_configurations = [] - stadium_configurations = [s.get_configuration() for s in MatchStadiumStatistics.objects.all()] - for s in stadium_configurations: - if s not in unique_stadium_configurations: - unique_stadium_configurations.append(s) - - context['seasons'] = sorted(seasons, reverse=True) - context['slider_min'] = slider_min - context['slider_max'] = slider_max - context['tolerance'] = tolerance - context['stadium_configurations'] = reversed(unique_stadium_configurations) - - return context - - -@method_decorator(login_required, name='dispatch') -class StadiumStatisticsAsJsonView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): - harmonic_strength = 150 - tolerance = 5 - if self.request.COOKIES.get('slider_min') and \ - self.request.COOKIES.get('slider_max') and \ - self.request.COOKIES.get('tolerance'): - slider_min = int(self.request.COOKIES['slider_min']) - slider_max = int(self.request.COOKIES['slider_max']) - tolerance = int(self.request.COOKIES['tolerance']) - harmonic_strength = round(2 * slider_min * slider_max / (slider_min + slider_max)) - harmonic_strength = self.request.GET.get('harmonic_strength', default=harmonic_strength) - tolerance = self.request.GET.get('tolerance', default=tolerance) - - try: - harmonic_strength = int(harmonic_strength) - tolerance = int(tolerance) - except TypeError: - pass - - matches = Match.objects.filter(user=self.request.user).order_by('matchday') - filtered_matches = [match for match in matches if - harmonic_strength - tolerance <= match.harmonic_strength <= harmonic_strength + tolerance] - - stadium_statistics = [] - for match in filtered_matches: - stat = MatchStadiumStatistics.objects.filter(match=match) - if stat.count() > 0: - stadium_statistics.append(stat[0]) - - stadium_configuration_filter = self.request.GET.get('configuration_filter') - filtered_stadium_stats = [] - if stadium_configuration_filter: - for stat in stadium_statistics: - if stat.get_configuration() == ast.literal_eval(stadium_configuration_filter): - filtered_stadium_stats.append(stat) - else: - filtered_stadium_stats = stadium_statistics - - stadium_statistics_json = [self._get_stadium_statistics_in_json(stat) for stat in filtered_stadium_stats] - - return self.render_json_response(stadium_statistics_json) - - @staticmethod - def _get_stadium_statistics_in_json(stadium_stat): - """ - Returns: - A dictionary of stadium statistics data. - """ - locale.setlocale(locale.LC_ALL, '') - - match_stadium_stat = dict() - match_stadium_stat['season'] = stadium_stat.match.matchday.season.number - match_stadium_stat['matchday'] = "" + str( - stadium_stat.match.matchday.number) + "" - if stadium_stat.visitors and stadium_stat.capacity: - match_stadium_stat['visitors'] = stadium_stat.visitors - match_stadium_stat['capacity'] = stadium_stat.capacity - match_stadium_stat['earnings'] = stadium_stat.earnings - match_stadium_stat['workload'] = locale.format("%.2f", - stadium_stat.visitors / - stadium_stat.capacity * 100) + " %" - else: - # all stadium stands were under construction during match - match_stadium_stat['visitors'] = 0 - match_stadium_stat['capacity'] = 0 - match_stadium_stat['earnings'] = 0 - match_stadium_stat['workload'] = 0 - match_stadium_stat['venue'] = stadium_stat.match.venue - home_strength = stadium_stat.match.home_team_statistics.strength - if home_strength == int(home_strength): - match_stadium_stat['home_strength'] = int(home_strength) - else: - match_stadium_stat['home_strength'] = locale.format("%.1f", home_strength) - guest_strength = stadium_stat.match.guest_team_statistics.strength - if guest_strength == int(guest_strength): - match_stadium_stat['guest_strength'] = int(guest_strength) - else: - match_stadium_stat['guest_strength'] = locale.format("%.1f", guest_strength) - harmonic_strength = 2 * home_strength * guest_strength / (home_strength + guest_strength) - match_stadium_stat['harmonic_strength'] = locale.format("%.1f", harmonic_strength) - match_stadium_stat['light_level'] = str(stadium_stat.level.light.current_level) + " (" + str( - stadium_stat.level.light.value) + " €) " + str(stadium_stat.level.light.daily_costs) + " €" - match_stadium_stat['screen_level'] = str(stadium_stat.level.screen.current_level) + " (" + str( - stadium_stat.level.screen.value) + " €) " + str(stadium_stat.level.screen.daily_costs) + " €" - match_stadium_stat['security_level'] = str(stadium_stat.level.security.current_level) + " (" + str( - stadium_stat.level.security.value) + " €) " + str( - stadium_stat.level.security.daily_costs) + " €" - match_stadium_stat['parking_level'] = str(stadium_stat.level.parking.current_level) + " (" + str( - stadium_stat.level.parking.value) + " €) " + str(stadium_stat.level.parking.daily_costs) + " €" - - return match_stadium_stat - - -@method_decorator(login_required, name='dispatch') -class StadiumDetailView(DetailView): - context_object_name = 'stadium_stat' - template_name = 'core/ofm/stadium_detail.html' - queryset = MatchStadiumStatistics.objects.all() - - def get_context_data(self, **kwargs): - context = super(StadiumDetailView, self).get_context_data(**kwargs) - - if self.get_object(): - north_stand = StadiumStandStatistics.objects.filter(stadium_statistics=self.get_object(), sector='N') - south_stand = StadiumStandStatistics.objects.filter(stadium_statistics=self.get_object(), sector='S') - west_stand = StadiumStandStatistics.objects.filter(stadium_statistics=self.get_object(), sector='W') - east_stand = StadiumStandStatistics.objects.filter(stadium_statistics=self.get_object(), sector='O') - - context['north_stand'] = north_stand[0] if north_stand.count() > 0 else None - context['south_stand'] = south_stand[0] if south_stand.count() > 0 else None - context['west_stand'] = west_stand[0] if west_stand.count() > 0 else None - context['east_stand'] = east_stand[0] if east_stand.count() > 0 else None - - return context - - def get_object(self, **kwargs): - stadium_stat = super(StadiumDetailView, self).get_object() - matches = Match.objects.filter(user=self.request.user, stadium_statistics=stadium_stat) - return stadium_stat if matches.count() > 0 else None - - -@method_decorator(login_required, name='dispatch') -class StadiumStandStatisticsView(TemplateView): - template_name = 'core/ofm/stadium_stand_statistics.html' - - def get_context_data(self, **kwargs): - context = super(StadiumStandStatisticsView, self).get_context_data(**kwargs) - - current_season_number = Matchday.objects.all()[0].season.number - sector = self.request.GET.get('sector', 'N') - season_number = self.request.GET.get('season', current_season_number) - queryset = StadiumStandStatistics.objects.filter( - stadium_statistics__match__user=self.request.user, - stadium_statistics__match__matchday__season__number=season_number, - sector=sector - ) - - seasons = [] - sectors = [] - statistics = StadiumStandStatistics.objects.filter( - stadium_statistics__match__user=self.request.user - ).order_by('stadium_statistics__match__matchday') - for stat in statistics: - if stat.stadium_statistics.match.matchday.season not in seasons: - seasons.append(stat.stadium_statistics.match.matchday.season) - if stat.get_sector() not in sectors: - sectors.append(stat.get_sector()) - - context['seasons'] = seasons - context['sectors'] = sectors - - context['sector'] = sector - context['season'] = season_number - if queryset.count() > 0: - context['sector_name'] = queryset[0].get_sector() - - return context - - -@method_decorator(login_required, name='dispatch') -class StadiumStandStatisticsChartView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): - current_season_number = Matchday.objects.all()[0].season.number - season_number = self.request.GET.get('season_number', default=current_season_number) - sector = self.request.GET.get('sector', 'N') - statistics = StadiumStandStatistics.objects.filter( - stadium_statistics__match__user=self.request.user, - stadium_statistics__match__matchday__season__number=season_number, - sector=sector - ) - - chart_json = { - "series": [{ - "name": 'Kapazität', - "data": [s.level.capacity for s in statistics], - "yAxis": 0 - }, { - "name": 'Zuschauer', - "data": [s.visitors for s in statistics], - "yAxis": 0 - }, { - "name": 'Ticketpreis', - "data": [s.ticket_price for s in statistics], - "yAxis": 1 - }, { - "name": 'Zustand', - "data": [float(s.condition) for s in statistics], - "yAxis": 1 - }, { - "name": 'Gemittelte Stärke der Mannschaften', - "data": [float("{0:.2f}".format(s.stadium_statistics.match.harmonic_strength)) for s in statistics], - "yAxis": 1 - }], - "categories": [s.stadium_statistics.match.matchday.number for s in statistics], - "yAxis": [{ - "title": { - "text": 'Kapazität & Zuschauer' - }, - 'min': 0 - }, { - "title": { - "text": 'Ticketpreis, Zustand & Stärke' - }, - 'min': 0, - "opposite": "true" - }] - } - - return self.render_json_response(chart_json) diff --git a/core/rename_me_views/__init__.py b/core/rename_me_views/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/rename_me_views/finance_views.py b/core/rename_me_views/finance_views.py new file mode 100644 index 0000000..a65e478 --- /dev/null +++ b/core/rename_me_views/finance_views.py @@ -0,0 +1,354 @@ +from braces.views import CsrfExemptMixin, JsonRequestResponseMixin +from django.contrib.auth.decorators import login_required +from django.utils.decorators import method_decorator +from django.views import View +from django.views.generic import TemplateView + +from core.models import Matchday, Finance +from core.rename_me_views.view_utils import validate_filtered_field + + +@method_decorator(login_required, name='dispatch') +class FinanceDataView(TemplateView): + template_name = 'core/ofm/finances.html' + + def get_context_data(self, **kwargs): + context = super(FinanceDataView, self).get_context_data(**kwargs) + matchdays = Matchday.objects.filter(finance__isnull=False).distinct() + context['matchdays'] = matchdays + + return context + + +@method_decorator(login_required, name='dispatch') +class FinancesAsJsonView(CsrfExemptMixin, JsonRequestResponseMixin, View): + def get(self, request, *args, **kwargs): + newer_matchday_season = self.request.GET.get('newer_matchday_season', + default=Matchday.objects.all()[0].season.number) + newer_matchday = self.request.GET.get('newer_matchday', default=Matchday.objects.all()[0].number) + older_matchday_season = self.request.GET.get('older_matchday_season') + older_matchday = self.request.GET.get('older_matchday') + + newer_finances = Finance.objects.filter( + user=request.user, + matchday__season__number=newer_matchday_season, + matchday__number=newer_matchday + ) + older_finances = Finance.objects.filter( + user=request.user, + matchday__season__number=older_matchday_season, + matchday__number=older_matchday + ) + + newer_finances = validate_filtered_field(newer_finances) + older_finances = validate_filtered_field(older_finances) + + finances_json = self._get_finances_diff_in_json(newer_finances, older_finances) + + return self.render_json_response(finances_json) + + @staticmethod + def _get_finances_diff_in_json(newer_finances, older_finances): + """ + Returns: + A dictionary of finance data. If older_finances is None newer_finances is returned + """ + + if not newer_finances: + newer_finances = Finance.objects.all().order_by('matchday')[0] + + account_balance = newer_finances.balance + + income_visitors_league = newer_finances.income_visitors_league + if older_finances: + income_visitors_league = newer_finances.income_visitors_league - older_finances.income_visitors_league + + income_sponsoring = newer_finances.income_sponsoring + if older_finances: + income_sponsoring = newer_finances.income_sponsoring - older_finances.income_sponsoring + + income_cup = newer_finances.income_cup + if older_finances: + income_cup = newer_finances.income_cup - older_finances.income_cup + + income_interests = newer_finances.income_interests + if older_finances: + income_interests = newer_finances.income_interests - older_finances.income_interests + + income_loan = newer_finances.income_loan + if older_finances: + income_loan = newer_finances.income_loan - older_finances.income_loan + + income_transfer = newer_finances.income_transfer + if older_finances: + income_transfer = newer_finances.income_transfer - older_finances.income_transfer + + income_visitors_friendlies = newer_finances.income_visitors_friendlies + if older_finances: + income_visitors_friendlies = newer_finances.income_visitors_friendlies - \ + older_finances.income_visitors_friendlies + + income_friendlies = newer_finances.income_friendlies + if older_finances: + income_friendlies = newer_finances.income_friendlies - older_finances.income_friendlies + + income_funcup = newer_finances.income_funcup + if older_finances: + income_funcup = newer_finances.income_funcup - older_finances.income_funcup + + income_betting = newer_finances.income_betting + if older_finances: + income_betting = newer_finances.income_betting - older_finances.income_betting + + expenses_player_salaries = -newer_finances.expenses_player_salaries + if older_finances: + expenses_player_salaries = -( + newer_finances.expenses_player_salaries - older_finances.expenses_player_salaries) + + expenses_stadium = -newer_finances.expenses_stadium + if older_finances: + expenses_stadium = -(newer_finances.expenses_stadium - older_finances.expenses_stadium) + + expenses_youth = -newer_finances.expenses_youth + if older_finances: + expenses_youth = -(newer_finances.expenses_youth - older_finances.expenses_youth) + + expenses_interests = -newer_finances.expenses_interests + if older_finances: + expenses_interests = -(newer_finances.expenses_interests - older_finances.expenses_interests) + + expenses_trainings = -newer_finances.expenses_trainings + if older_finances: + expenses_trainings = -(newer_finances.expenses_trainings - older_finances.expenses_trainings) + + expenses_transfer = -newer_finances.expenses_transfer + if older_finances: + expenses_transfer = -(newer_finances.expenses_transfer - older_finances.expenses_transfer) + + expenses_compensation = -newer_finances.expenses_compensation + if older_finances: + expenses_compensation = -(newer_finances.expenses_compensation - older_finances.expenses_compensation) + + expenses_friendlies = -newer_finances.expenses_friendlies + if older_finances: + expenses_friendlies = -(newer_finances.expenses_friendlies - older_finances.expenses_friendlies) + + expenses_funcup = -newer_finances.expenses_funcup + if older_finances: + expenses_funcup = -(newer_finances.expenses_funcup - older_finances.expenses_funcup) + + expenses_betting = -newer_finances.expenses_betting + if older_finances: + expenses_betting = -(newer_finances.expenses_betting - older_finances.expenses_betting) + + finances_diff = dict() + finances_diff['account_balance'] = account_balance + + finances_diff['income_visitors_league'] = income_visitors_league + finances_diff['income_sponsoring'] = income_sponsoring + finances_diff['income_cup'] = income_cup + finances_diff['income_interests'] = income_interests + finances_diff['income_loan'] = income_loan + finances_diff['income_transfer'] = income_transfer + finances_diff['income_visitors_friendlies'] = income_visitors_friendlies + finances_diff['income_friendlies'] = income_friendlies + finances_diff['income_funcup'] = income_funcup + finances_diff['income_betting'] = income_betting + + finances_diff['expenses_player_salaries'] = expenses_player_salaries + finances_diff['expenses_stadium'] = expenses_stadium + finances_diff['expenses_youth'] = expenses_youth + finances_diff['expenses_interests'] = expenses_interests + finances_diff['expenses_trainings'] = expenses_trainings + finances_diff['expenses_transfer'] = expenses_transfer + finances_diff['expenses_compensation'] = expenses_compensation + finances_diff['expenses_friendlies'] = expenses_friendlies + finances_diff['expenses_funcup'] = expenses_funcup + finances_diff['expenses_betting'] = expenses_betting + + sum_income = income_visitors_league + income_sponsoring + income_cup + income_interests + income_loan + \ + income_transfer + income_visitors_friendlies + income_friendlies + income_funcup + income_betting + sum_expenses = expenses_player_salaries + expenses_stadium + expenses_youth + expenses_interests + \ + expenses_trainings + expenses_transfer + expenses_compensation + expenses_friendlies + \ + expenses_funcup + expenses_betting + + finances_diff['sum_income'] = sum_income + finances_diff['sum_expenses'] = sum_expenses + finances_diff['balance'] = sum_income + sum_expenses + + return [finances_diff] + + +@method_decorator(login_required, name='dispatch') +class FinanceBalanceChartView(CsrfExemptMixin, JsonRequestResponseMixin, View): + def get(self, request, *args, **kwargs): + current_season_number = Matchday.objects.all()[0].season.number + season_number = self.request.GET.get('season_number', default=current_season_number) + data_source = Finance.objects.filter(user=self.request.user, matchday__season__number=season_number) + + chart_json = { + "series": [{ + "name": 'Kontostand', + "data": [finance.balance for finance in data_source] + }], + "categories": [finance.matchday.number for finance in data_source] + } + + return self.render_json_response(chart_json) + + +@method_decorator(login_required, name='dispatch') +class FinanceIncomeChartView(CsrfExemptMixin, JsonRequestResponseMixin, View): + def get(self, request, *args, **kwargs): + current_season_number = Matchday.objects.all()[0].season.number + season_number = self.request.GET.get('season_number', default=current_season_number) + data_source = Finance.objects.filter(user=self.request.user, matchday__season__number=season_number) + + income_visitors_league = [] + income_sponsoring = [] + income_cup = [] + income_interests = [] + income_loan = [] + income_transfer = [] + income_visitors_friendlies = [] + income_friendlies = [] + income_funcup = [] + income_betting = [] + matchdays = [] + + if len(data_source) >= 1: + income_visitors_league.append(data_source[0].income_visitors_league) + income_sponsoring.append(data_source[0].income_sponsoring) + income_cup.append(data_source[0].income_cup) + income_interests.append(data_source[0].income_interests) + income_loan.append(data_source[0].income_loan) + income_transfer.append(data_source[0].income_transfer) + income_visitors_friendlies.append(data_source[0].income_visitors_friendlies) + income_friendlies.append(data_source[0].income_friendlies) + income_funcup.append(data_source[0].income_funcup) + income_betting.append(data_source[0].income_betting) + matchdays.append(data_source[0].matchday.number) + + for idx, _ in enumerate(data_source): + if idx + 1 < data_source.count(): + income_visitors_league.append( + data_source[idx + 1].income_visitors_league - data_source[idx].income_visitors_league) + income_sponsoring.append(data_source[idx + 1].income_sponsoring - data_source[idx].income_sponsoring) + income_cup.append(data_source[idx + 1].income_cup - data_source[idx].income_cup) + income_interests.append(data_source[idx + 1].income_interests - data_source[idx].income_interests) + income_loan.append(data_source[idx + 1].income_loan - data_source[idx].income_loan) + income_transfer.append(data_source[idx + 1].income_transfer - data_source[idx].income_transfer) + income_visitors_friendlies.append( + data_source[idx + 1].income_visitors_friendlies - data_source[idx].income_visitors_friendlies) + income_friendlies.append(data_source[idx + 1].income_friendlies - data_source[idx].income_friendlies) + income_funcup.append(data_source[idx + 1].income_funcup - data_source[idx].income_funcup) + income_betting.append(data_source[idx + 1].income_betting - data_source[idx].income_betting) + matchdays.append(data_source[idx + 1].matchday.number) + + series = [] + if sum(income_visitors_league) is not 0: + series.append({"name": 'Ticketeinnahmen Liga', "data": income_visitors_league}) + if sum(income_sponsoring) is not 0: + series.append({"name": 'Sponsor', "data": income_sponsoring}) + if sum(income_cup) is not 0: + series.append({"name": 'Pokal', "data": income_cup}) + if sum(income_interests) is not 0: + series.append({"name": 'Zinsen', "data": income_interests}) + if sum(income_loan) is not 0: + series.append({"name": 'Kredite', "data": income_loan}) + if sum(income_transfer) is not 0: + series.append({"name": 'Spielertransfers', "data": income_transfer}) + if sum(income_visitors_friendlies) is not 0: + series.append({"name": 'Ticketeinnahmen Freundschaftsspiele', "data": income_visitors_friendlies}) + if sum(income_friendlies) is not 0: + series.append({"name": 'Freundschaftsspiele', "data": income_friendlies}) + if sum(income_funcup) is not 0: + series.append({"name": 'Fun-Cup', "data": income_funcup}) + if sum(income_betting) is not 0: + series.append({"name": 'Wetten', "data": income_betting}) + + chart_json = { + "series": series, + "categories": matchdays + } + + return self.render_json_response(chart_json) + + +@method_decorator(login_required, name='dispatch') +class FinanceExpensesChartView(CsrfExemptMixin, JsonRequestResponseMixin, View): + def get(self, request, *args, **kwargs): + current_season_number = Matchday.objects.all()[0].season.number + season_number = self.request.GET.get('season_number', default=current_season_number) + data_source = Finance.objects.filter(user=self.request.user, matchday__season__number=season_number) + + expenses_player_salaries = [] + expenses_stadium = [] + expenses_youth = [] + expenses_interests = [] + expenses_trainings = [] + expenses_transfer = [] + expenses_compensation = [] + expenses_friendlies = [] + expenses_funcup = [] + expenses_betting = [] + matchdays = [] + + if len(data_source) >= 1: + expenses_player_salaries.append(-data_source[0].expenses_player_salaries) + expenses_stadium.append(-data_source[0].expenses_stadium) + expenses_youth.append(-data_source[0].expenses_youth) + expenses_interests.append(-data_source[0].expenses_interests) + expenses_trainings.append(-data_source[0].expenses_trainings) + expenses_transfer.append(-data_source[0].expenses_transfer) + expenses_compensation.append(-data_source[0].expenses_compensation) + expenses_friendlies.append(-data_source[0].expenses_friendlies) + expenses_funcup.append(-data_source[0].expenses_funcup) + expenses_betting.append(-data_source[0].expenses_betting) + matchdays.append(data_source[0].matchday.number) + + for idx, _ in enumerate(data_source): + if idx + 1 < data_source.count(): + expenses_player_salaries.append( + data_source[idx].expenses_player_salaries - data_source[idx + 1].expenses_player_salaries) + expenses_stadium.append(data_source[idx].expenses_stadium - data_source[idx + 1].expenses_stadium) + expenses_youth.append(data_source[idx].expenses_youth - data_source[idx + 1].expenses_youth) + expenses_interests.append(data_source[idx].expenses_interests - data_source[idx + 1].expenses_interests) + expenses_trainings.append(data_source[idx].expenses_trainings - data_source[idx + 1].expenses_trainings) + expenses_transfer.append(data_source[idx].expenses_transfer - data_source[idx + 1].expenses_transfer) + expenses_compensation.append( + data_source[idx].expenses_compensation - data_source[idx + 1].expenses_compensation) + expenses_friendlies.append( + data_source[idx].expenses_friendlies - data_source[idx + 1].expenses_friendlies) + expenses_funcup.append(data_source[idx].expenses_funcup - data_source[idx + 1].expenses_funcup) + expenses_betting.append(data_source[idx].expenses_betting - data_source[idx + 1].expenses_betting) + matchdays.append(data_source[idx + 1].matchday.number) + + series = [] + if sum(expenses_player_salaries) is not 0: + series.append({"name": 'Spielergehalt', "data": expenses_player_salaries}) + if sum(expenses_stadium) is not 0: + series.append({"name": 'Stadion', "data": expenses_stadium}) + if sum(expenses_youth) is not 0: + series.append({"name": u'Jugendförderung', "data": expenses_youth}) + if sum(expenses_interests) is not 0: + series.append({"name": 'Zinsen', "data": expenses_interests}) + if sum(expenses_trainings) is not 0: + series.append({"name": 'Training', "data": expenses_trainings}) + if sum(expenses_transfer) is not 0: + series.append({"name": 'Spielertransfers', "data": expenses_transfer}) + if sum(expenses_compensation) is not 0: + series.append({"name": 'Abfindungen', "data": expenses_compensation}) + if sum(expenses_friendlies) is not 0: + series.append({"name": 'Freundschaftsspiele', "data": expenses_friendlies}) + if sum(expenses_funcup) is not 0: + series.append({"name": 'Fun-Cup', "data": expenses_funcup}) + if sum(expenses_betting) is not 0: + series.append({"name": 'Wetten', "data": expenses_betting}) + + chart_json = { + "series": series, + "categories": matchdays + } + + return self.render_json_response(chart_json) diff --git a/core/rename_me_views/match_views.py b/core/rename_me_views/match_views.py new file mode 100644 index 0000000..a26d12b --- /dev/null +++ b/core/rename_me_views/match_views.py @@ -0,0 +1,113 @@ +import locale + +from braces.views import CsrfExemptMixin, JsonRequestResponseMixin +from django.contrib.auth.decorators import login_required +from django.utils.decorators import method_decorator +from django.views import View +from django.views.generic import TemplateView + +from core.models import Matchday, Match + + +@method_decorator(login_required, name='dispatch') +class MatchesView(TemplateView): + template_name = 'core/ofm/matches.html' + + def get_context_data(self, **kwargs): + context = super(MatchesView, self).get_context_data(**kwargs) + + matchdays = Matchday.objects.filter(matches__isnull=False).distinct() + seasons = set(m.season.number for m in matchdays) + + context['seasons'] = sorted(seasons, reverse=True) + + return context + + +@method_decorator(login_required, name='dispatch') +class MatchesAsJsonView(CsrfExemptMixin, JsonRequestResponseMixin, View): + def get(self, request, *args, **kwargs): + season = self.request.GET.get('season', default=Matchday.objects.all()[0].season.number) + matches = Match.objects.filter(user=self.request.user, matchday__season__number=season) + + match_json = [self._get_match_in_json(match) for match in matches] + + return self.render_json_response(match_json) + + @staticmethod + def _get_match_in_json(match): + """ + Returns: + A dictionary of match data. + """ + locale.setlocale(locale.LC_ALL, '') + + if match.is_home_match: + home_team_name = "" + match.home_team_statistics.team_name + "" + guest_team_name = match.guest_team_statistics.team_name + if hasattr(match, 'stadium_statistics'): + venue = "" + match.venue + "" + else: + venue = match.venue + else: + home_team_name = match.home_team_statistics.team_name + guest_team_name = "" + match.guest_team_statistics.team_name + "" + venue = match.venue + + result_score = str(match.home_team_statistics.score) + ":" + str(match.guest_team_statistics.score) + if match.is_in_future: + result = "-:-" + elif match.is_won: + result = "" + result_score + "" + elif match.is_draw: + result = "" + result_score + "" + else: + result = "" + result_score + "" + + match_stat = dict() + match_stat['home_team'] = home_team_name + match_stat['guest_team'] = guest_team_name + match_stat['result'] = result + home_strength = match.home_team_statistics.strength + if home_strength == int(home_strength): + match_stat['home_strength'] = int(home_strength) + else: + match_stat['home_strength'] = locale.format("%.1f", home_strength) + guest_strength = match.guest_team_statistics.strength + if guest_strength == int(guest_strength): + match_stat['guest_strength'] = int(guest_strength) + else: + match_stat['guest_strength'] = locale.format("%.1f", guest_strength) + match_stat['home_ball_possession'] = locale.format("%.1f", match.home_team_statistics.ball_possession) + " %" + match_stat['guest_ball_possession'] = locale.format("%.1f", match.guest_team_statistics.ball_possession) + " %" + match_stat['home_chances'] = match.home_team_statistics.chances + match_stat['guest_chances'] = match.guest_team_statistics.chances + match_stat['home_yellow_cards'] = match.home_team_statistics.yellow_cards + match_stat['guest_yellow_cards'] = match.guest_team_statistics.yellow_cards + match_stat['home_red_cards'] = match.home_team_statistics.red_cards + match_stat['guest_red_cards'] = match.guest_team_statistics.red_cards + match_stat['venue'] = venue + match_stat['matchday'] = match.matchday.number + + return match_stat + + +@method_decorator(login_required, name='dispatch') +class MatchesSummaryJsonView(CsrfExemptMixin, JsonRequestResponseMixin, View): + def get(self, request, *args, **kwargs): + current_season = Matchday.objects.all()[0].season + season_number = self.request.GET.get('season_number', current_season.number) + matches_won = len( + [match for match in Match.objects.filter(matchday__season__number=season_number) if match.is_won]) + matches_draw = len( + [match for match in Match.objects.filter(matchday__season__number=season_number) if match.is_draw]) + matches_lost = len( + [match for match in Match.objects.filter(matchday__season__number=season_number) if match.is_lost]) + + json = { + "matches_won": matches_won, + "matches_draw": matches_draw, + "matches_lost": matches_lost + } + + return self.render_json_response(json) diff --git a/core/rename_me_views/player_views.py b/core/rename_me_views/player_views.py new file mode 100644 index 0000000..9bac683 --- /dev/null +++ b/core/rename_me_views/player_views.py @@ -0,0 +1,196 @@ +from braces.views import CsrfExemptMixin, JsonRequestResponseMixin +from django.contrib.auth.decorators import login_required +from django.utils.decorators import method_decorator +from django.views import View +from django.views.generic import TemplateView, DetailView + +from core.models import Matchday, Contract, PlayerStatistics, AwpBoundaries, Player +from core.rename_me_views.view_utils import validate_filtered_field + + +@method_decorator(login_required, name='dispatch') +class PlayerStatisticsView(TemplateView): + template_name = 'core/ofm/player_statistics.html' + + def get_context_data(self, **kwargs): + matchdays = Matchday.objects.filter(player_statistics__isnull=False).distinct() + + context = super(PlayerStatisticsView, self).get_context_data(**kwargs) + context['matchdays'] = matchdays + context['players_count'] = Contract.objects.filter(user=self.request.user, sold_on_matchday=None).count() + + return context + + +@method_decorator(login_required, name='dispatch') +class PlayerStatisticsAsJsonView(CsrfExemptMixin, JsonRequestResponseMixin, View): + def get(self, request, *args, **kwargs): + contracts = Contract.objects.filter(user=self.request.user, sold_on_matchday=None) + players = [contract.player for contract in contracts] + current_matchday = Matchday.objects.all()[0] + + newer_matchday_season = self.request.GET.get('newer_matchday_season', default=current_matchday.season.number) + newer_matchday = self.request.GET.get('newer_matchday', default=current_matchday.number) + older_matchday_season = self.request.GET.get('older_matchday_season') + older_matchday = self.request.GET.get('older_matchday') + diff_mode_enabled = older_matchday and older_matchday_season + + player_statistics_tuples = [] + for player in players: + newer_player_statistics, older_player_statistics = self._get_statistics_from_player_and_matchday( + player, + newer_matchday_season, newer_matchday, + older_matchday_season, older_matchday + ) + if newer_player_statistics and (older_player_statistics or not diff_mode_enabled): + player_statistics_tuples.append((newer_player_statistics, older_player_statistics)) + + player_statistics_json = [ + self._get_player_statistics_diff_in_json(newer_player_statistics, older_player_statistics) + for (newer_player_statistics, older_player_statistics) in player_statistics_tuples + ] + + return self.render_json_response(player_statistics_json) + + @staticmethod + def _get_statistics_from_player_and_matchday(player, + newer_matchday_season, newer_matchday, + older_matchday_season, older_matchday): + + newer_player_statistics = PlayerStatistics.objects.filter( + player=player, + matchday__season__number=newer_matchday_season, + matchday__number=newer_matchday + ) + older_player_statistics = PlayerStatistics.objects.filter( + player=player, + matchday__season__number=older_matchday_season, + matchday__number=older_matchday + ) + + newer_player_statistics = validate_filtered_field(newer_player_statistics) + older_player_statistics = validate_filtered_field(older_player_statistics) + + if not newer_player_statistics: + newer_player_statistics = PlayerStatistics.objects.filter( + player=player, + matchday__season__number=newer_matchday_season + ).order_by('matchday')[0] + + return newer_player_statistics, older_player_statistics + + @staticmethod + def _get_player_statistics_diff_in_json(newer_player_statistics, older_player_statistics): + """ + Args: + newer_player_statistics: newer statistic + older_player_statistics: older statistic + + Returns: + A dictionary of player statistics data. If st2 is None st1 is returned + """ + + strength = newer_player_statistics.strength + if older_player_statistics: + strength = newer_player_statistics.strength - older_player_statistics.strength + ep = newer_player_statistics.ep + if older_player_statistics: + ep = newer_player_statistics.ep - older_player_statistics.ep + tp = newer_player_statistics.tp + if older_player_statistics: + tp = newer_player_statistics.tp - older_player_statistics.tp + awp = newer_player_statistics.awp + if older_player_statistics: + awp = newer_player_statistics.awp - older_player_statistics.awp + freshness = newer_player_statistics.freshness + if older_player_statistics: + freshness = newer_player_statistics.freshness - older_player_statistics.freshness + + awp_boundaries = AwpBoundaries.get_from_matchday(newer_player_statistics.matchday) + awp_to_next_bound = awp_boundaries[newer_player_statistics.strength + 1] - newer_player_statistics.awp + + statistic_diff = dict() + statistic_diff['position'] = newer_player_statistics.player.position + statistic_diff['age'] = newer_player_statistics.age + statistic_diff['strength'] = strength + statistic_diff['name'] = '%s' % (newer_player_statistics.player.get_absolute_url(), + newer_player_statistics.player.name) + statistic_diff['ep'] = ep + statistic_diff['tp'] = tp + statistic_diff['awp'] = awp + statistic_diff['freshness'] = freshness + statistic_diff['games_in_season'] = newer_player_statistics.games_in_season + statistic_diff['goals_in_season'] = newer_player_statistics.goals_in_season + statistic_diff['won_tacklings_in_season'] = newer_player_statistics.won_tacklings_in_season + statistic_diff['lost_tacklings_in_season'] = newer_player_statistics.lost_tacklings_in_season + statistic_diff['won_friendly_tacklings_in_season'] = newer_player_statistics.won_friendly_tacklings_in_season + statistic_diff['lost_friendly_tacklings_in_season'] = newer_player_statistics.lost_friendly_tacklings_in_season + statistic_diff['yellow_cards_in_season'] = newer_player_statistics.yellow_cards_in_season + statistic_diff['red_cards_in_season'] = newer_player_statistics.red_cards_in_season + statistic_diff['equity'] = newer_player_statistics.equity + statistic_diff['awp_to_next_bound'] = awp_to_next_bound + + return statistic_diff + + +@method_decorator(login_required, name='dispatch') +class PlayerDetailView(DetailView): + context_object_name = 'player' + template_name = 'core/ofm/player_detail.html' + queryset = Player.objects.all() + + def get_context_data(self, **kwargs): + context = super(PlayerDetailView, self).get_context_data(**kwargs) + + player = self.get_object() + current_season = Matchday.objects.all()[0].season + seasons = [] + player_stats = PlayerStatistics.objects.filter(player=player).order_by('matchday') + for player_stat in player_stats: + if player_stat.matchday.season not in seasons: + seasons.append(player_stat.matchday.season) + + context['seasons'] = seasons + if player: + context['player_age'] = current_season.number - player.birth_season.number + context['player_strength'] = player_stats[0].strength + + return context + + def get_object(self, **kwargs): + player = super(PlayerDetailView, self).get_object() + contracts = Contract.objects.filter(user=self.request.user, player=player, sold_on_matchday=None) + return player if contracts.count() > 0 else None + + +@method_decorator(login_required, name='dispatch') +class PlayerChartView(CsrfExemptMixin, JsonRequestResponseMixin, View): + def get(self, request, *args, **kwargs): + current_season_number = Matchday.objects.all()[0].season.number + season_number = self.request.GET.get('season_number', default=current_season_number) + player_id = self.request.GET.get('player_id') + player = Player.objects.filter(id=player_id) + player_statistics = PlayerStatistics.objects.filter(player=player, matchday__season__number=season_number) + awps = [player_stat.awp for player_stat in player_statistics] + + chart_json = { + "series": [{ + "name": 'AWP', + "data": awps + }], + "categories": [player_stat.matchday.number for player_stat in player_statistics] + } + + matchdays = [p.matchday for p in player_statistics] + current_player_statistics = PlayerStatistics.objects.filter(player=player).order_by('matchday')[0] + + current_awp_boundaries = AwpBoundaries.get_from_matchday(current_player_statistics.matchday) + + for strength in current_awp_boundaries: + if current_awp_boundaries[strength] >= min(awps) and strength > current_player_statistics.strength: + awp_boundary_values = [AwpBoundaries.get_from_matchday(matchday)[strength] for matchday in matchdays] + chart_json['series'].append({'name': 'AWP-Grenze: %s' % strength, 'data': awp_boundary_values}) + if current_awp_boundaries[strength] >= max(awps): + break + + return self.render_json_response(chart_json) diff --git a/core/rename_me_views/stadium_views.py b/core/rename_me_views/stadium_views.py new file mode 100644 index 0000000..1185c11 --- /dev/null +++ b/core/rename_me_views/stadium_views.py @@ -0,0 +1,264 @@ +import ast +import locale + +from braces.views import CsrfExemptMixin, JsonRequestResponseMixin +from django.contrib.auth.decorators import login_required +from django.utils.decorators import method_decorator +from django.views import View +from django.views.generic import TemplateView, DetailView + +from core.models import Matchday, Match, MatchStadiumStatistics, StadiumStandStatistics + + +@method_decorator(login_required, name='dispatch') +class StadiumStatisticsView(TemplateView): + template_name = 'core/ofm/stadium_statistics.html' + + def get_context_data(self, **kwargs): + context = super(StadiumStatisticsView, self).get_context_data(**kwargs) + + matchdays = Matchday.objects.filter(matches__isnull=False).distinct() + seasons = set(m.season.number for m in matchdays) + + tolerance = 5 + if self.request.COOKIES.get('slider_min') and \ + self.request.COOKIES.get('slider_max') and \ + self.request.COOKIES.get('tolerance'): + slider_min = self.request.COOKIES['slider_min'] + slider_max = self.request.COOKIES['slider_max'] + tolerance = self.request.COOKIES['tolerance'] + elif Match.objects.count() > 0: + # latest home match + match = Match.objects.filter(user=self.request.user, is_home_match=True).order_by('matchday')[0] + slider_min = int(min(match.home_team_statistics.strength, match.guest_team_statistics.strength)) + slider_max = int(max(match.home_team_statistics.strength, match.guest_team_statistics.strength)) + else: + slider_min = 100 + slider_max = 150 + + unique_stadium_configurations = [] + stadium_configurations = [s.get_configuration() for s in MatchStadiumStatistics.objects.all()] + for s in stadium_configurations: + if s not in unique_stadium_configurations: + unique_stadium_configurations.append(s) + + context['seasons'] = sorted(seasons, reverse=True) + context['slider_min'] = slider_min + context['slider_max'] = slider_max + context['tolerance'] = tolerance + context['stadium_configurations'] = reversed(unique_stadium_configurations) + + return context + + +@method_decorator(login_required, name='dispatch') +class StadiumStatisticsAsJsonView(CsrfExemptMixin, JsonRequestResponseMixin, View): + def get(self, request, *args, **kwargs): + harmonic_strength = 150 + tolerance = 5 + if self.request.COOKIES.get('slider_min') and \ + self.request.COOKIES.get('slider_max') and \ + self.request.COOKIES.get('tolerance'): + slider_min = int(self.request.COOKIES['slider_min']) + slider_max = int(self.request.COOKIES['slider_max']) + tolerance = int(self.request.COOKIES['tolerance']) + harmonic_strength = round(2 * slider_min * slider_max / (slider_min + slider_max)) + harmonic_strength = self.request.GET.get('harmonic_strength', default=harmonic_strength) + tolerance = self.request.GET.get('tolerance', default=tolerance) + + try: + harmonic_strength = int(harmonic_strength) + tolerance = int(tolerance) + except TypeError: + pass + + matches = Match.objects.filter(user=self.request.user).order_by('matchday') + filtered_matches = [match for match in matches if + harmonic_strength - tolerance <= match.harmonic_strength <= harmonic_strength + tolerance] + + stadium_statistics = [] + for match in filtered_matches: + stat = MatchStadiumStatistics.objects.filter(match=match) + if stat.count() > 0: + stadium_statistics.append(stat[0]) + + stadium_configuration_filter = self.request.GET.get('configuration_filter') + filtered_stadium_stats = [] + if stadium_configuration_filter: + for stat in stadium_statistics: + if stat.get_configuration() == ast.literal_eval(stadium_configuration_filter): + filtered_stadium_stats.append(stat) + else: + filtered_stadium_stats = stadium_statistics + + stadium_statistics_json = [self._get_stadium_statistics_in_json(stat) for stat in filtered_stadium_stats] + + return self.render_json_response(stadium_statistics_json) + + @staticmethod + def _get_stadium_statistics_in_json(stadium_stat): + """ + Returns: + A dictionary of stadium statistics data. + """ + locale.setlocale(locale.LC_ALL, '') + + match_stadium_stat = dict() + match_stadium_stat['season'] = stadium_stat.match.matchday.season.number + match_stadium_stat['matchday'] = "" + str( + stadium_stat.match.matchday.number) + "" + if stadium_stat.visitors and stadium_stat.capacity: + match_stadium_stat['visitors'] = stadium_stat.visitors + match_stadium_stat['capacity'] = stadium_stat.capacity + match_stadium_stat['earnings'] = stadium_stat.earnings + match_stadium_stat['workload'] = locale.format("%.2f", + stadium_stat.visitors / + stadium_stat.capacity * 100) + " %" + else: + # all stadium stands were under construction during match + match_stadium_stat['visitors'] = 0 + match_stadium_stat['capacity'] = 0 + match_stadium_stat['earnings'] = 0 + match_stadium_stat['workload'] = 0 + match_stadium_stat['venue'] = stadium_stat.match.venue + home_strength = stadium_stat.match.home_team_statistics.strength + if home_strength == int(home_strength): + match_stadium_stat['home_strength'] = int(home_strength) + else: + match_stadium_stat['home_strength'] = locale.format("%.1f", home_strength) + guest_strength = stadium_stat.match.guest_team_statistics.strength + if guest_strength == int(guest_strength): + match_stadium_stat['guest_strength'] = int(guest_strength) + else: + match_stadium_stat['guest_strength'] = locale.format("%.1f", guest_strength) + harmonic_strength = 2 * home_strength * guest_strength / (home_strength + guest_strength) + match_stadium_stat['harmonic_strength'] = locale.format("%.1f", harmonic_strength) + match_stadium_stat['light_level'] = str(stadium_stat.level.light.current_level) + " (" + str( + stadium_stat.level.light.value) + " €) " + str(stadium_stat.level.light.daily_costs) + " €" + match_stadium_stat['screen_level'] = str(stadium_stat.level.screen.current_level) + " (" + str( + stadium_stat.level.screen.value) + " €) " + str(stadium_stat.level.screen.daily_costs) + " €" + match_stadium_stat['security_level'] = str(stadium_stat.level.security.current_level) + " (" + str( + stadium_stat.level.security.value) + " €) " + str( + stadium_stat.level.security.daily_costs) + " €" + match_stadium_stat['parking_level'] = str(stadium_stat.level.parking.current_level) + " (" + str( + stadium_stat.level.parking.value) + " €) " + str(stadium_stat.level.parking.daily_costs) + " €" + + return match_stadium_stat + + +@method_decorator(login_required, name='dispatch') +class StadiumDetailView(DetailView): + context_object_name = 'stadium_stat' + template_name = 'core/ofm/stadium_detail.html' + queryset = MatchStadiumStatistics.objects.all() + + def get_context_data(self, **kwargs): + context = super(StadiumDetailView, self).get_context_data(**kwargs) + + if self.get_object(): + north_stand = StadiumStandStatistics.objects.filter(stadium_statistics=self.get_object(), sector='N') + south_stand = StadiumStandStatistics.objects.filter(stadium_statistics=self.get_object(), sector='S') + west_stand = StadiumStandStatistics.objects.filter(stadium_statistics=self.get_object(), sector='W') + east_stand = StadiumStandStatistics.objects.filter(stadium_statistics=self.get_object(), sector='O') + + context['north_stand'] = north_stand[0] if north_stand.count() > 0 else None + context['south_stand'] = south_stand[0] if south_stand.count() > 0 else None + context['west_stand'] = west_stand[0] if west_stand.count() > 0 else None + context['east_stand'] = east_stand[0] if east_stand.count() > 0 else None + + return context + + def get_object(self, **kwargs): + stadium_stat = super(StadiumDetailView, self).get_object() + matches = Match.objects.filter(user=self.request.user, stadium_statistics=stadium_stat) + return stadium_stat if matches.count() > 0 else None + + +@method_decorator(login_required, name='dispatch') +class StadiumStandStatisticsView(TemplateView): + template_name = 'core/ofm/stadium_stand_statistics.html' + + def get_context_data(self, **kwargs): + context = super(StadiumStandStatisticsView, self).get_context_data(**kwargs) + + current_season_number = Matchday.objects.all()[0].season.number + sector = self.request.GET.get('sector', 'N') + season_number = self.request.GET.get('season', current_season_number) + queryset = StadiumStandStatistics.objects.filter( + stadium_statistics__match__user=self.request.user, + stadium_statistics__match__matchday__season__number=season_number, + sector=sector + ) + + seasons = [] + sectors = [] + statistics = StadiumStandStatistics.objects.filter( + stadium_statistics__match__user=self.request.user + ).order_by('stadium_statistics__match__matchday') + for stat in statistics: + if stat.stadium_statistics.match.matchday.season not in seasons: + seasons.append(stat.stadium_statistics.match.matchday.season) + if stat.get_sector() not in sectors: + sectors.append(stat.get_sector()) + + context['seasons'] = seasons + context['sectors'] = sectors + + context['sector'] = sector + context['season'] = season_number + if queryset.count() > 0: + context['sector_name'] = queryset[0].get_sector() + + return context + + +@method_decorator(login_required, name='dispatch') +class StadiumStandStatisticsChartView(CsrfExemptMixin, JsonRequestResponseMixin, View): + def get(self, request, *args, **kwargs): + current_season_number = Matchday.objects.all()[0].season.number + season_number = self.request.GET.get('season_number', default=current_season_number) + sector = self.request.GET.get('sector', 'N') + statistics = StadiumStandStatistics.objects.filter( + stadium_statistics__match__user=self.request.user, + stadium_statistics__match__matchday__season__number=season_number, + sector=sector + ) + + chart_json = { + "series": [{ + "name": 'Kapazität', + "data": [s.level.capacity for s in statistics], + "yAxis": 0 + }, { + "name": 'Zuschauer', + "data": [s.visitors for s in statistics], + "yAxis": 0 + }, { + "name": 'Ticketpreis', + "data": [s.ticket_price for s in statistics], + "yAxis": 1 + }, { + "name": 'Zustand', + "data": [float(s.condition) for s in statistics], + "yAxis": 1 + }, { + "name": 'Gemittelte Stärke der Mannschaften', + "data": [float("{0:.2f}".format(s.stadium_statistics.match.harmonic_strength)) for s in statistics], + "yAxis": 1 + }], + "categories": [s.stadium_statistics.match.matchday.number for s in statistics], + "yAxis": [{ + "title": { + "text": 'Kapazität & Zuschauer' + }, + 'min': 0 + }, { + "title": { + "text": 'Ticketpreis, Zustand & Stärke' + }, + 'min': 0, + "opposite": "true" + }] + } + + return self.render_json_response(chart_json) diff --git a/core/rename_me_views/view_utils.py b/core/rename_me_views/view_utils.py new file mode 100644 index 0000000..e5dee4d --- /dev/null +++ b/core/rename_me_views/view_utils.py @@ -0,0 +1,9 @@ +from django.core.exceptions import MultipleObjectsReturned + + +def validate_filtered_field(field): + if len(field) > 1: + raise MultipleObjectsReturned + elif field: + field = field[0] + return field diff --git a/core/urls.py b/core/urls.py index 2086704..3333009 100644 --- a/core/urls.py +++ b/core/urls.py @@ -2,6 +2,7 @@ from django.views.generic.base import TemplateView, RedirectView from core import views + from core.views import CreateChecklistItemView, DeleteChecklistItemView, GetChecklistItemsView, \ UpdateChecklistItemView, GetChecklistItemsForTodayView, GetCurrentMatchdayView, UpdateChecklistPriorityView From 342aa72cd0f2e89f8450b2e69bf5b0e85f92a516 Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Sat, 10 Dec 2016 21:30:33 +0100 Subject: [PATCH 29/71] #99 more moving of views --- .../__init__.py | 0 core/localizations/__init__.py | 0 core/localizations/messages.py | 4 + core/ofm_urls.py | 10 +-- core/tests/unit/views/test_parser_view.py | 20 ++--- core/urls.py | 28 +++---- core/views/__init__.py | 0 core/{views.py => views/base_views.py} | 78 +------------------ .../finance_views.py | 2 +- .../{rename_me_views => views}/match_views.py | 0 .../player_views.py | 2 +- .../stadium_views.py | 0 core/views/trigger_parsing_views.py | 72 +++++++++++++++++ core/{rename_me_views => views}/view_utils.py | 0 14 files changed, 110 insertions(+), 106 deletions(-) rename core/{rename_me_views => localization}/__init__.py (100%) create mode 100644 core/localizations/__init__.py create mode 100644 core/localizations/messages.py create mode 100644 core/views/__init__.py rename core/{views.py => views/base_views.py} (84%) rename core/{rename_me_views => views}/finance_views.py (99%) rename core/{rename_me_views => views}/match_views.py (100%) rename core/{rename_me_views => views}/player_views.py (99%) rename core/{rename_me_views => views}/stadium_views.py (100%) create mode 100644 core/views/trigger_parsing_views.py rename core/{rename_me_views => views}/view_utils.py (100%) diff --git a/core/rename_me_views/__init__.py b/core/localization/__init__.py similarity index 100% rename from core/rename_me_views/__init__.py rename to core/localization/__init__.py diff --git a/core/localizations/__init__.py b/core/localizations/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/localizations/messages.py b/core/localizations/messages.py new file mode 100644 index 0000000..f21c83a --- /dev/null +++ b/core/localizations/messages.py @@ -0,0 +1,4 @@ +MSG_NOT_LOGGED_IN = "Du bist nicht eingeloggt!" +MSG_SETTINGS_SAVED = "Die neuen Einstellungen wurden gespeichert." +MSG_PASSWORDS_UNEQUAL = "Die eingegeben Passwörter stimmen nicht überein." +MSG_OFM_PASSWORDS_UNEQUAL = "Die eingegeben OFM Passwörter stimmen nicht überein." diff --git a/core/ofm_urls.py b/core/ofm_urls.py index 979d88a..2394ade 100644 --- a/core/ofm_urls.py +++ b/core/ofm_urls.py @@ -1,11 +1,11 @@ from django.conf.urls import url -from core.rename_me_views.stadium_views import StadiumStatisticsView, StadiumStatisticsAsJsonView, StadiumDetailView, \ - StadiumStandStatisticsView, StadiumStandStatisticsChartView -from core.rename_me_views.match_views import MatchesView, MatchesAsJsonView, MatchesSummaryJsonView -from core.rename_me_views.finance_views import FinanceDataView, FinancesAsJsonView, FinanceBalanceChartView, \ +from core.views.finance_views import FinanceDataView, FinancesAsJsonView, FinanceBalanceChartView, \ FinanceIncomeChartView, FinanceExpensesChartView -from core.rename_me_views.player_views import PlayerStatisticsView, PlayerStatisticsAsJsonView, PlayerDetailView, PlayerChartView +from core.views.match_views import MatchesView, MatchesAsJsonView, MatchesSummaryJsonView +from core.views.player_views import PlayerStatisticsView, PlayerStatisticsAsJsonView, PlayerDetailView, PlayerChartView +from core.views.stadium_views import StadiumStatisticsView, StadiumStatisticsAsJsonView, StadiumDetailView, \ + StadiumStandStatisticsView, StadiumStandStatisticsChartView app_name = 'ofm' urlpatterns = [ diff --git a/core/tests/unit/views/test_parser_view.py b/core/tests/unit/views/test_parser_view.py index bef7746..f39cfe3 100644 --- a/core/tests/unit/views/test_parser_view.py +++ b/core/tests/unit/views/test_parser_view.py @@ -18,27 +18,27 @@ def setUp(self): self.user = OFMUser.objects.create_user('name', '', 'pass', ofm_username='name', ofm_password='pass') self.client.login(username='name', password='pass') - @patch('core.views.SiteManager') + @patch('core.views.trigger_parsing_views.SiteManager') @patch('core.managers.parser_manager.MatchdayParser') def test_matchday_parser_view(self, site_manager_mock, matchday_parser_mock): response = self.client.get(reverse('core:trigger_matchday_parsing')) self.assertEqual(response.status_code, 302) - assert core.views.SiteManager.called + assert core.views.trigger_parsing_views.SiteManager.called assert core.managers.parser_manager.MatchdayParser.return_value.parse.called - @patch('core.views.SiteManager') + @patch('core.views.trigger_parsing_views.SiteManager') @patch('core.managers.parser_manager.MatchdayParser') @patch('core.managers.parser_manager.PlayersParser') def test_player_parser_view(self, matchday_parser_mock, site_manager_mock, players_parser_mock): response = self.client.get(reverse('core:trigger_players_parsing')) self.assertEqual(response.status_code, 302) - assert core.views.SiteManager.called + assert core.views.trigger_parsing_views.SiteManager.called assert core.managers.parser_manager.MatchdayParser.return_value.parse.called assert core.managers.parser_manager.PlayersParser.return_value.parse.called - @patch('core.views.SiteManager') + @patch('core.views.trigger_parsing_views.SiteManager') @patch('core.managers.parser_manager.MatchdayParser') @patch('core.managers.parser_manager.PlayersParser') @patch('core.managers.parser_manager.PlayerStatisticsParser') @@ -47,19 +47,19 @@ def test_player_statistics_parser_view(self, matchday_parser_mock, player_parser response = self.client.get(reverse('core:trigger_player_statistics_parsing')) self.assertEqual(response.status_code, 302) - assert core.views.SiteManager.called + assert core.views.trigger_parsing_views.SiteManager.called assert core.managers.parser_manager.MatchdayParser.return_value.parse.called assert core.managers.parser_manager.PlayersParser.return_value.parse.called assert core.managers.parser_manager.PlayerStatisticsParser.return_value.parse.called - @patch('core.views.SiteManager') + @patch('core.views.trigger_parsing_views.SiteManager') @patch('core.managers.parser_manager.MatchdayParser') @patch('core.managers.parser_manager.FinancesParser') def test_finances_parser_view(self, matchday_parser_mock, site_manager_mock, finances_parser_mock): response = self.client.get(reverse('core:trigger_finances_parsing')) self.assertEqual(response.status_code, 302) - assert core.views.SiteManager.called + assert core.views.trigger_parsing_views.SiteManager.called assert core.managers.parser_manager.MatchdayParser.return_value.parse.called assert core.managers.parser_manager.FinancesParser.return_value.parse.called @@ -68,7 +68,7 @@ def test_finances_parser_view(self, matchday_parser_mock, site_manager_mock, fin @patch('core.managers.parser_manager.ParserManager._parse_stadium_statistics') def test_match_parser_view(self, matchday_parser_mock, match_parser_mock, parse_stadium_statistics_mock): with open(os.path.join(TESTDATA_PATH, 'match_schedule.html'), encoding='utf8') as match_schedule_html: - with patch('core.views.SiteManager') as site_manager_mock: + with patch('core.views.trigger_parsing_views.SiteManager') as site_manager_mock: site_manager_instance_mock = site_manager_mock.return_value site_manager_instance_mock.browser.page_source = match_schedule_html @@ -79,7 +79,7 @@ def test_match_parser_view(self, matchday_parser_mock, match_parser_mock, parse_ assert core.managers.parser_manager.MatchParser.return_value.parse.called assert parse_stadium_statistics_mock.called - @patch('core.views.SiteManager') + @patch('core.views.trigger_parsing_views.SiteManager') @patch('core.managers.parser_manager.ParserManager.parse_matchday') @patch('core.managers.parser_manager.ParserManager.parse_players') @patch('core.managers.parser_manager.ParserManager.parse_player_statistics') diff --git a/core/urls.py b/core/urls.py index 3333009..3ccf03c 100644 --- a/core/urls.py +++ b/core/urls.py @@ -1,23 +1,23 @@ from django.conf.urls import url, include from django.views.generic.base import TemplateView, RedirectView -from core import views - -from core.views import CreateChecklistItemView, DeleteChecklistItemView, GetChecklistItemsView, \ +import core.views.trigger_parsing_views +from core.views import base_views +from core.views.base_views import CreateChecklistItemView, DeleteChecklistItemView, GetChecklistItemsView, \ UpdateChecklistItemView, GetChecklistItemsForTodayView, GetCurrentMatchdayView, UpdateChecklistPriorityView app_name = 'core' urlpatterns = [ url(r'^favicon\.ico$', RedirectView.as_view(url='/static/core/img/OFM_favicon.png', permanent=True)), url(r'^$', TemplateView.as_view(template_name='core/home.html'), name='home'), - url(r'^register/?$', views.register_view, name='register'), - url(r'^login/?$', views.login_view, name='login'), - url(r'^account/?$', views.account_view, name='account'), - url(r'^logout/?$', views.logout_view, name='logout'), + url(r'^register/?$', base_views.register_view, name='register'), + url(r'^login/?$', base_views.login_view, name='login'), + url(r'^account/?$', base_views.account_view, name='account'), + url(r'^logout/?$', base_views.logout_view, name='logout'), url(r'^ofm/', include('core.ofm_urls'), name='ofm'), url(r'^get_current_matchday/?$', GetCurrentMatchdayView.as_view(), name='get_current_matchday'), - url(r'^settings/?$', views.settings_view, name='settings'), + url(r'^settings/?$', base_views.settings_view, name='settings'), url(r'^settings_get_checklist_items/?$', GetChecklistItemsView.as_view(), name='settings_get_checklist_items'), url(r'^settings_get_checklist_items_for_today/?$', GetChecklistItemsForTodayView.as_view(), name='settings_get_checklist_items_for_today'), @@ -29,11 +29,11 @@ url(r'^settings_update_checklist_priority/?$', UpdateChecklistPriorityView.as_view(), name='settings_update_checklist_priority'), - url(r'^trigger_parsing/?$', views.trigger_parsing, name='trigger_parsing'), - url(r'^trigger_matchday_parsing/?$', views.trigger_matchday_parsing, name='trigger_matchday_parsing'), - url(r'^trigger_players_parsing/?$', views.trigger_players_parsing, name='trigger_players_parsing'), - url(r'^trigger_player_statistics_parsing/?$', views.trigger_player_statistics_parsing, + url(r'^trigger_parsing/?$', core.views.trigger_parsing_views.trigger_parsing, name='trigger_parsing'), + url(r'^trigger_matchday_parsing/?$', core.views.trigger_parsing_views.trigger_matchday_parsing, name='trigger_matchday_parsing'), + url(r'^trigger_players_parsing/?$', core.views.trigger_parsing_views.trigger_players_parsing, name='trigger_players_parsing'), + url(r'^trigger_player_statistics_parsing/?$', core.views.trigger_parsing_views.trigger_player_statistics_parsing, name='trigger_player_statistics_parsing'), - url(r'^trigger_finances_parsing/?$', views.trigger_finances_parsing, name='trigger_finances_parsing'), - url(r'^trigger_match_parsing/?$', views.trigger_match_parsing, name='trigger_match_parsing'), + url(r'^trigger_finances_parsing/?$', core.views.trigger_parsing_views.trigger_finances_parsing, name='trigger_finances_parsing'), + url(r'^trigger_match_parsing/?$', core.views.trigger_parsing_views.trigger_match_parsing, name='trigger_match_parsing'), ] diff --git a/core/views/__init__.py b/core/views/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/core/views.py b/core/views/base_views.py similarity index 84% rename from core/views.py rename to core/views/base_views.py index c6e1adc..104f201 100644 --- a/core/views.py +++ b/core/views/base_views.py @@ -1,5 +1,4 @@ -from braces.views import CsrfExemptMixin -from braces.views import JsonRequestResponseMixin +from braces.views import CsrfExemptMixin, JsonRequestResponseMixin from django.contrib import messages from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required @@ -7,16 +6,11 @@ from django.utils.decorators import method_decorator from django.views.generic import View -from core.managers.parser_manager import ParserManager -from core.managers.site_manager import SiteManager +from core.localizations.messages import MSG_NOT_LOGGED_IN, MSG_SETTINGS_SAVED, MSG_PASSWORDS_UNEQUAL, \ + MSG_OFM_PASSWORDS_UNEQUAL from core.models import ChecklistItem, Checklist, Matchday, Match from users.models import OFMUser -MSG_NOT_LOGGED_IN = "Du bist nicht eingeloggt!" -MSG_SETTINGS_SAVED = "Die neuen Einstellungen wurden gespeichert." -MSG_PASSWORDS_UNEQUAL = "Die eingegeben Passwörter stimmen nicht überein." -MSG_OFM_PASSWORDS_UNEQUAL = "Die eingegeben OFM Passwörter stimmen nicht überein." - def register_view(request): if request.user.is_authenticated(): @@ -311,69 +305,3 @@ def account_view(request): else: messages.error(request, MSG_NOT_LOGGED_IN) return redirect('core:login') - - -def trigger_parsing(request): - if request.user.is_authenticated(): - site_manager = SiteManager(request.user) - site_manager.login() - - pm = ParserManager() - pm.parse_all_ofm_data(request, site_manager) - - remote_version = pm.parse_ofm_version(site_manager) - try: - with open('version', 'r') as version_file: - own_version = version_file.read().replace('\n', '') - if own_version != "null" and own_version != remote_version: - messages.info(request, "Es ist eine neuere Version von OFM Helper verfügbar: %s. Du nutzt noch: %s." % ( - remote_version, own_version)) - except IOError: - pass - - site_manager.kill() - - return redirect('core:ofm:player_statistics') - else: - messages.error(request, MSG_NOT_LOGGED_IN) - return redirect('core:login') - - -def trigger_single_parsing(request, parsing_function, redirect_to='core:account'): - if request.user.is_authenticated(): - site_manager = SiteManager(request.user) - site_manager.login() - parsing_function(request, site_manager) - return redirect(redirect_to) - else: - messages.error(request, MSG_NOT_LOGGED_IN) - return redirect('core:login') - - -def trigger_matchday_parsing(request): - pm = ParserManager() - return trigger_single_parsing(request, pm.parse_matchday) - - -def trigger_players_parsing(request): - pm = ParserManager() - redirect_to = 'core:ofm:player_statistics' - return trigger_single_parsing(request, pm.parse_players, redirect_to) - - -def trigger_player_statistics_parsing(request): - pm = ParserManager() - redirect_to = 'core:ofm:player_statistics' - return trigger_single_parsing(request, pm.parse_player_statistics, redirect_to) - - -def trigger_finances_parsing(request): - pm = ParserManager() - redirect_to = 'core:ofm:finance_overview' - return trigger_single_parsing(request, pm.parse_finances, redirect_to) - - -def trigger_match_parsing(request): - pm = ParserManager() - redirect_to = 'core:ofm:matches_overview' - return trigger_single_parsing(request, pm.parse_all_matches, redirect_to) diff --git a/core/rename_me_views/finance_views.py b/core/views/finance_views.py similarity index 99% rename from core/rename_me_views/finance_views.py rename to core/views/finance_views.py index a65e478..e5636bf 100644 --- a/core/rename_me_views/finance_views.py +++ b/core/views/finance_views.py @@ -5,7 +5,7 @@ from django.views.generic import TemplateView from core.models import Matchday, Finance -from core.rename_me_views.view_utils import validate_filtered_field +from core.views.view_utils import validate_filtered_field @method_decorator(login_required, name='dispatch') diff --git a/core/rename_me_views/match_views.py b/core/views/match_views.py similarity index 100% rename from core/rename_me_views/match_views.py rename to core/views/match_views.py diff --git a/core/rename_me_views/player_views.py b/core/views/player_views.py similarity index 99% rename from core/rename_me_views/player_views.py rename to core/views/player_views.py index 9bac683..863cda8 100644 --- a/core/rename_me_views/player_views.py +++ b/core/views/player_views.py @@ -5,7 +5,7 @@ from django.views.generic import TemplateView, DetailView from core.models import Matchday, Contract, PlayerStatistics, AwpBoundaries, Player -from core.rename_me_views.view_utils import validate_filtered_field +from core.views.view_utils import validate_filtered_field @method_decorator(login_required, name='dispatch') diff --git a/core/rename_me_views/stadium_views.py b/core/views/stadium_views.py similarity index 100% rename from core/rename_me_views/stadium_views.py rename to core/views/stadium_views.py diff --git a/core/views/trigger_parsing_views.py b/core/views/trigger_parsing_views.py new file mode 100644 index 0000000..115aeb4 --- /dev/null +++ b/core/views/trigger_parsing_views.py @@ -0,0 +1,72 @@ +from django.contrib import messages +from django.shortcuts import redirect + +from core.localizations.messages import MSG_NOT_LOGGED_IN +from core.managers.parser_manager import ParserManager +from core.managers.site_manager import SiteManager + + +def trigger_parsing(request): + if request.user.is_authenticated(): + site_manager = SiteManager(request.user) + site_manager.login() + + pm = ParserManager() + pm.parse_all_ofm_data(request, site_manager) + + remote_version = pm.parse_ofm_version(site_manager) + try: + with open('version', 'r') as version_file: + own_version = version_file.read().replace('\n', '') + if own_version != "null" and own_version != remote_version: + messages.info(request, "Es ist eine neuere Version von OFM Helper verfügbar: %s. Du nutzt noch: %s." % ( + remote_version, own_version)) + except IOError: + pass + + site_manager.kill() + + return redirect('core:ofm:player_statistics') + else: + messages.error(request, MSG_NOT_LOGGED_IN) + return redirect('core:login') + + +def trigger_single_parsing(request, parsing_function, redirect_to='core:account'): + if request.user.is_authenticated(): + site_manager = SiteManager(request.user) + site_manager.login() + parsing_function(request, site_manager) + return redirect(redirect_to) + else: + messages.error(request, MSG_NOT_LOGGED_IN) + return redirect('core:login') + + +def trigger_matchday_parsing(request): + pm = ParserManager() + return trigger_single_parsing(request, pm.parse_matchday) + + +def trigger_players_parsing(request): + pm = ParserManager() + redirect_to = 'core:ofm:player_statistics' + return trigger_single_parsing(request, pm.parse_players, redirect_to) + + +def trigger_player_statistics_parsing(request): + pm = ParserManager() + redirect_to = 'core:ofm:player_statistics' + return trigger_single_parsing(request, pm.parse_player_statistics, redirect_to) + + +def trigger_finances_parsing(request): + pm = ParserManager() + redirect_to = 'core:ofm:finance_overview' + return trigger_single_parsing(request, pm.parse_finances, redirect_to) + + +def trigger_match_parsing(request): + pm = ParserManager() + redirect_to = 'core:ofm:matches_overview' + return trigger_single_parsing(request, pm.parse_all_matches, redirect_to) diff --git a/core/rename_me_views/view_utils.py b/core/views/view_utils.py similarity index 100% rename from core/rename_me_views/view_utils.py rename to core/views/view_utils.py From bf198ae069a3b54df59d2ca424098191367275e3 Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Sat, 10 Dec 2016 21:45:23 +0100 Subject: [PATCH 30/71] #99 reorganzing views package --- .../messages.py | 1 + core/ofm_urls.py | 8 +- core/urls.py | 18 +- core/views/account_views.py | 92 ++++++ core/views/base_views.py | 291 +----------------- core/views/checklist_views.py | 158 ++++++++++ core/{localizations => views/ofm}/__init__.py | 0 core/views/{ => ofm}/finance_views.py | 0 core/views/{ => ofm}/match_views.py | 0 core/views/{ => ofm}/player_views.py | 0 core/views/{ => ofm}/stadium_views.py | 0 core/views/settings_views.py | 53 ++++ core/views/trigger_parsing_views.py | 5 +- 13 files changed, 321 insertions(+), 305 deletions(-) rename core/{localizations => localization}/messages.py (71%) create mode 100644 core/views/account_views.py create mode 100644 core/views/checklist_views.py rename core/{localizations => views/ofm}/__init__.py (100%) rename core/views/{ => ofm}/finance_views.py (100%) rename core/views/{ => ofm}/match_views.py (100%) rename core/views/{ => ofm}/player_views.py (100%) rename core/views/{ => ofm}/stadium_views.py (100%) create mode 100644 core/views/settings_views.py diff --git a/core/localizations/messages.py b/core/localization/messages.py similarity index 71% rename from core/localizations/messages.py rename to core/localization/messages.py index f21c83a..90a4019 100644 --- a/core/localizations/messages.py +++ b/core/localization/messages.py @@ -2,3 +2,4 @@ MSG_SETTINGS_SAVED = "Die neuen Einstellungen wurden gespeichert." MSG_PASSWORDS_UNEQUAL = "Die eingegeben Passwörter stimmen nicht überein." MSG_OFM_PASSWORDS_UNEQUAL = "Die eingegeben OFM Passwörter stimmen nicht überein." +NEWER_OFM_VERSION_AVAILABLE = "Es ist eine neuere Version von OFM Helper verfügbar: %s. Du nutzt noch: %s." diff --git a/core/ofm_urls.py b/core/ofm_urls.py index 2394ade..b46e471 100644 --- a/core/ofm_urls.py +++ b/core/ofm_urls.py @@ -1,10 +1,10 @@ from django.conf.urls import url -from core.views.finance_views import FinanceDataView, FinancesAsJsonView, FinanceBalanceChartView, \ +from core.views.ofm.finance_views import FinanceDataView, FinancesAsJsonView, FinanceBalanceChartView, \ FinanceIncomeChartView, FinanceExpensesChartView -from core.views.match_views import MatchesView, MatchesAsJsonView, MatchesSummaryJsonView -from core.views.player_views import PlayerStatisticsView, PlayerStatisticsAsJsonView, PlayerDetailView, PlayerChartView -from core.views.stadium_views import StadiumStatisticsView, StadiumStatisticsAsJsonView, StadiumDetailView, \ +from core.views.ofm.match_views import MatchesView, MatchesAsJsonView, MatchesSummaryJsonView +from core.views.ofm.player_views import PlayerStatisticsView, PlayerStatisticsAsJsonView, PlayerDetailView, PlayerChartView +from core.views.ofm.stadium_views import StadiumStatisticsView, StadiumStatisticsAsJsonView, StadiumDetailView, \ StadiumStandStatisticsView, StadiumStandStatisticsChartView app_name = 'ofm' diff --git a/core/urls.py b/core/urls.py index 3ccf03c..6d52da5 100644 --- a/core/urls.py +++ b/core/urls.py @@ -1,23 +1,25 @@ from django.conf.urls import url, include from django.views.generic.base import TemplateView, RedirectView +import core.views.account_views +import core.views.settings_views import core.views.trigger_parsing_views -from core.views import base_views -from core.views.base_views import CreateChecklistItemView, DeleteChecklistItemView, GetChecklistItemsView, \ - UpdateChecklistItemView, GetChecklistItemsForTodayView, GetCurrentMatchdayView, UpdateChecklistPriorityView +from core.views.base_views import GetCurrentMatchdayView +from core.views.checklist_views import GetChecklistItemsView, GetChecklistItemsForTodayView, CreateChecklistItemView, \ + UpdateChecklistPriorityView, UpdateChecklistItemView, DeleteChecklistItemView app_name = 'core' urlpatterns = [ url(r'^favicon\.ico$', RedirectView.as_view(url='/static/core/img/OFM_favicon.png', permanent=True)), url(r'^$', TemplateView.as_view(template_name='core/home.html'), name='home'), - url(r'^register/?$', base_views.register_view, name='register'), - url(r'^login/?$', base_views.login_view, name='login'), - url(r'^account/?$', base_views.account_view, name='account'), - url(r'^logout/?$', base_views.logout_view, name='logout'), + url(r'^register/?$', core.views.account_views.register_view, name='register'), + url(r'^login/?$', core.views.account_views.login_view, name='login'), + url(r'^account/?$', core.views.account_views.account_view, name='account'), + url(r'^logout/?$', core.views.account_views.logout_view, name='logout'), url(r'^ofm/', include('core.ofm_urls'), name='ofm'), url(r'^get_current_matchday/?$', GetCurrentMatchdayView.as_view(), name='get_current_matchday'), - url(r'^settings/?$', base_views.settings_view, name='settings'), + url(r'^settings/?$', core.views.settings_views.settings_view, name='settings'), url(r'^settings_get_checklist_items/?$', GetChecklistItemsView.as_view(), name='settings_get_checklist_items'), url(r'^settings_get_checklist_items_for_today/?$', GetChecklistItemsForTodayView.as_view(), name='settings_get_checklist_items_for_today'), diff --git a/core/views/account_views.py b/core/views/account_views.py new file mode 100644 index 0000000..6dc3a11 --- /dev/null +++ b/core/views/account_views.py @@ -0,0 +1,92 @@ +from django.contrib import messages +from django.contrib.auth import authenticate, login, logout +from django.shortcuts import render, redirect + +from core.localization.messages import MSG_PASSWORDS_UNEQUAL, MSG_OFM_PASSWORDS_UNEQUAL, MSG_NOT_LOGGED_IN +from users.models import OFMUser + + +def register_view(request): + if request.user.is_authenticated(): + messages.error(request, "Du bist bereits eingeloggt. Du kannst dich im Menü ausloggen.") + return render(request, 'core/account/home.html') + if request.POST: + username = request.POST.get('username') + email = request.POST.get('email') + password = request.POST.get('password') + password2 = request.POST.get('password2') + ofm_username = request.POST.get('ofm_username') + ofm_password = request.POST.get('ofm_password') + ofm_password2 = request.POST.get('ofm_password2') + + if OFMUser.objects.filter(email=email).exists(): + messages.error(request, "Ein Account mit dieser E-Mail-Adresse existiert bereits.") + return redirect('core:register') + + if OFMUser.objects.filter(username=username).exists(): + messages.error(request, "Ein Account mit diesem Benutzernamen existiert bereits.") + return redirect('core:register') + + if password != password2: + messages.error(request, MSG_PASSWORDS_UNEQUAL) + return redirect('core:register') + + if OFMUser.objects.filter(ofm_username=ofm_username).exists(): + messages.error(request, "Es existiert bereits ein Account für diesen OFM Benutzernamen.") + return redirect('core:register') + + if ofm_password != ofm_password2: + messages.error(request, MSG_OFM_PASSWORDS_UNEQUAL) + return redirect('core:register') + + OFMUser.objects.create_user( + username=username, + email=email, + password=password, + ofm_username=ofm_username, + ofm_password=ofm_password, + ) + + messages.success(request, "Account wurde erstellt. Jetzt kannst du dich einloggen.") + return redirect('core:login') + + else: + return render(request, 'core/account/register.html') + + +def login_view(request): + if request.POST: + username = request.POST.get('username') + password = request.POST.get('password') + user = authenticate(username=username, password=password) + if user is not None: + if user.is_active: + login(request, user) + messages.success(request, "Login erfolgreich.") + return render(request, 'core/account/home.html') + else: + messages.error(request, "Login nicht möglich. Dein Account wurde deaktiviert.") + return redirect('core:login') + else: + messages.error(request, "Benutzername und/oder Passwort nicht korrekt.") + return redirect('core:login') + else: + if request.user.is_authenticated(): + return render(request, 'core/account/home.html') + else: + return render(request, 'core/account/login.html') + + +def logout_view(request): + if request.user.is_authenticated(): + logout(request) + messages.success(request, "Du wurdest abgemeldet.") + return redirect('core:home') + + +def account_view(request): + if request.user.is_authenticated(): + return render(request, 'core/account/home.html') + else: + messages.error(request, MSG_NOT_LOGGED_IN) + return redirect('core:login') diff --git a/core/views/base_views.py b/core/views/base_views.py index 104f201..e58bd29 100644 --- a/core/views/base_views.py +++ b/core/views/base_views.py @@ -1,133 +1,9 @@ from braces.views import CsrfExemptMixin, JsonRequestResponseMixin -from django.contrib import messages -from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required -from django.shortcuts import redirect, render from django.utils.decorators import method_decorator from django.views.generic import View -from core.localizations.messages import MSG_NOT_LOGGED_IN, MSG_SETTINGS_SAVED, MSG_PASSWORDS_UNEQUAL, \ - MSG_OFM_PASSWORDS_UNEQUAL -from core.models import ChecklistItem, Checklist, Matchday, Match -from users.models import OFMUser - - -def register_view(request): - if request.user.is_authenticated(): - messages.error(request, "Du bist bereits eingeloggt. Du kannst dich im Menü ausloggen.") - return render(request, 'core/account/home.html') - if request.POST: - username = request.POST.get('username') - email = request.POST.get('email') - password = request.POST.get('password') - password2 = request.POST.get('password2') - ofm_username = request.POST.get('ofm_username') - ofm_password = request.POST.get('ofm_password') - ofm_password2 = request.POST.get('ofm_password2') - - if OFMUser.objects.filter(email=email).exists(): - messages.error(request, "Ein Account mit dieser E-Mail-Adresse existiert bereits.") - return redirect('core:register') - - if OFMUser.objects.filter(username=username).exists(): - messages.error(request, "Ein Account mit diesem Benutzernamen existiert bereits.") - return redirect('core:register') - - if password != password2: - messages.error(request, MSG_PASSWORDS_UNEQUAL) - return redirect('core:register') - - if OFMUser.objects.filter(ofm_username=ofm_username).exists(): - messages.error(request, "Es existiert bereits ein Account für diesen OFM Benutzernamen.") - return redirect('core:register') - - if ofm_password != ofm_password2: - messages.error(request, MSG_OFM_PASSWORDS_UNEQUAL) - return redirect('core:register') - - OFMUser.objects.create_user( - username=username, - email=email, - password=password, - ofm_username=ofm_username, - ofm_password=ofm_password, - ) - - messages.success(request, "Account wurde erstellt. Jetzt kannst du dich einloggen.") - return redirect('core:login') - - else: - return render(request, 'core/account/register.html') - - -def login_view(request): - if request.POST: - username = request.POST.get('username') - password = request.POST.get('password') - user = authenticate(username=username, password=password) - if user is not None: - if user.is_active: - login(request, user) - messages.success(request, "Login erfolgreich.") - return render(request, 'core/account/home.html') - else: - messages.error(request, "Login nicht möglich. Dein Account wurde deaktiviert.") - return redirect('core:login') - else: - messages.error(request, "Benutzername und/oder Passwort nicht korrekt.") - return redirect('core:login') - else: - if request.user.is_authenticated(): - return render(request, 'core/account/home.html') - else: - return render(request, 'core/account/login.html') - - -def _handle_account_data_change(request, email, password, password2): - if email: - if OFMUser.objects.filter(email=email).exclude(id=request.user.id).exists(): - messages.error(request, "Ein anderer Account existiert bereits mit dieser E-Mail-Adresse.") - return - request.user.email = email - if password and password2: - if password != password2: - messages.error(request, MSG_PASSWORDS_UNEQUAL) - return - request.user.set_password(password) - request.user.save() - messages.success(request, MSG_SETTINGS_SAVED) - - -def _handle_ofm_data_change(request, ofm_password, ofm_password2): - if ofm_password != ofm_password2: - messages.error(request, MSG_OFM_PASSWORDS_UNEQUAL) - return redirect('core:register') - - request.user.ofm_password = ofm_password - request.user.save() - messages.success(request, MSG_SETTINGS_SAVED) - - -def settings_view(request): - if request.user.is_authenticated(): - if request.POST: - email = request.POST.get('email') - password = request.POST.get('password') - password2 = request.POST.get('password2') - ofm_password = request.POST.get('ofm_password') - ofm_password2 = request.POST.get('ofm_password2') - - if email or (password and password2): - _handle_account_data_change(request, email, password, password2) - elif ofm_password and ofm_password2: - _handle_ofm_data_change(request, ofm_password, ofm_password2) - else: - messages.error(request, "Die Daten waren nicht vollständig. Bitte überprüfe die Eingabe.") - - return render(request, 'core/account/settings.html') - else: - messages.error(request, MSG_NOT_LOGGED_IN) - return redirect('core:login') +from core.models import Matchday @method_decorator(login_required, name='dispatch') @@ -140,168 +16,3 @@ def get(self, request, *args, **kwargs): return self.render_json_response(matchday_json) -@method_decorator(login_required, name='dispatch') -class GetChecklistItemsView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): - checklist_items = ChecklistItem.objects.filter(checklist__user=request.user) - - checklist_items_json = [_get_checklist_item_in_json(item) for item in checklist_items] - - return self.render_json_response(checklist_items_json) - - -@method_decorator(login_required, name='dispatch') -class GetChecklistItemsForTodayView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): - current_matchday = Matchday.get_current() - home_match_tomorrow = Match.objects.filter( - user=request.user, - matchday__season__number=current_matchday.season.number, - matchday__number=current_matchday.number + 1, - is_home_match=True - ) - checklist_items = ChecklistItem.objects.filter(checklist__user=request.user) - checklist_items_everyday = checklist_items.filter( - to_be_checked_on_matchdays=None, - to_be_checked_on_matchday_pattern=None, - to_be_checked_if_home_match_tomorrow=False - ) - filtered_checklist_items = [] - filtered_checklist_items.extend(checklist_items_everyday) - checklist_items_this_matchday = checklist_items.filter( - to_be_checked_on_matchdays__isnull=False, - to_be_checked_on_matchday_pattern=None, - to_be_checked_if_home_match_tomorrow=False - ) - filtered_checklist_items.extend([c for c in checklist_items_this_matchday if - current_matchday.number in [int(x) for x in - c.to_be_checked_on_matchdays.split(',')]]) - if home_match_tomorrow: - checklist_items_home_match = checklist_items.filter( - to_be_checked_on_matchdays=None, - to_be_checked_on_matchday_pattern=None, - to_be_checked_if_home_match_tomorrow=True - ) - filtered_checklist_items.extend(checklist_items_home_match) - if current_matchday.number > 0: - checklist_items_matchday_pattern_pre = checklist_items.filter( - to_be_checked_on_matchdays=None, - to_be_checked_on_matchday_pattern__isnull=False, - to_be_checked_if_home_match_tomorrow=False - ) - checklist_items_matchday_pattern = [c for c - in checklist_items_matchday_pattern_pre - if current_matchday.number % c.to_be_checked_on_matchday_pattern == 0] - filtered_checklist_items.extend(checklist_items_matchday_pattern) - - sorted_checklist_items = sorted(filtered_checklist_items, key=lambda x: x.priority, reverse=False) - checklist_items_json = [_get_checklist_item_in_json(item) for item in sorted_checklist_items] - - return self.render_json_response(checklist_items_json) - - -def _get_checklist_item_in_json(checklist_item): - checklist_item_json = dict() - checklist_item_json['id'] = checklist_item.id - checklist_item_json['name'] = checklist_item.name - if checklist_item.to_be_checked_if_home_match_tomorrow: - checklist_item_json['type_home_match'] = checklist_item.to_be_checked_if_home_match_tomorrow - if checklist_item.to_be_checked_on_matchdays is not None: - checklist_item_json['type_matchdays'] = checklist_item.to_be_checked_on_matchdays - if checklist_item.to_be_checked_on_matchday_pattern is not None: - checklist_item_json['type_matchday_pattern'] = checklist_item.to_be_checked_on_matchday_pattern - checklist_item_json['checked'] = checklist_item.last_checked_on_matchday == Matchday.get_current() - - return checklist_item_json - - -@method_decorator(login_required, name='dispatch') -class CreateChecklistItemView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def get(self, request, *args, **kwargs): - checklist, _ = Checklist.objects.get_or_create(user=request.user) - new_checklist_item = ChecklistItem.objects.create(checklist=checklist, name='Neuer Eintrag') - - new_checklist_item_json = _get_checklist_item_in_json(new_checklist_item) - - return self.render_json_response(new_checklist_item_json) - - -@method_decorator(login_required, name='dispatch') -class UpdateChecklistPriorityView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def post(self, request, *args, **kwargs): - checklist_priority = request.POST.get('checklist_priority') - - priority = [int(x) for x in checklist_priority.split(',')] - for checklist_item_id in priority: - checklist_item = ChecklistItem.objects.get(checklist__user=request.user, id=checklist_item_id) - checklist_item.priority = priority.index(checklist_item_id) - checklist_item.save() - - return self.render_json_response({'success': True}) - - -@method_decorator(login_required, name='dispatch') -class UpdateChecklistItemView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def post(self, request, *args, **kwargs): - checklist_item_id = request.POST.get('checklist_item_id') - checklist_item_name = request.POST.get('checklist_item_name') - checklist_item_matchdays = request.POST.get('checklist_item_matchdays') - checklist_item_matchday_pattern = request.POST.get('checklist_item_matchday_pattern') - checklist_item_home_match = request.POST.get('checklist_item_home_match') - checklist_item_everyday = request.POST.get('checklist_item_everyday') - checklist_item_checked = request.POST.get('checklist_item_checked') - - checklist_item = ChecklistItem.objects.get(checklist__user=request.user, id=checklist_item_id) - - if checklist_item: - if checklist_item_name: - checklist_item.name = checklist_item_name - elif checklist_item_matchdays: - checklist_item.to_be_checked_on_matchdays = checklist_item_matchdays - checklist_item.to_be_checked_on_matchday_pattern = None - checklist_item.to_be_checked_if_home_match_tomorrow = False - elif checklist_item_matchday_pattern: - checklist_item.to_be_checked_on_matchdays = None - checklist_item.to_be_checked_on_matchday_pattern = checklist_item_matchday_pattern - checklist_item.to_be_checked_if_home_match_tomorrow = False - elif checklist_item_home_match: - checklist_item.to_be_checked_on_matchdays = None - checklist_item.to_be_checked_on_matchday_pattern = None - checklist_item.to_be_checked_if_home_match_tomorrow = True - elif checklist_item_everyday: - checklist_item.to_be_checked_on_matchdays = None - checklist_item.to_be_checked_on_matchday_pattern = None - checklist_item.to_be_checked_if_home_match_tomorrow = False - elif checklist_item_checked == 'true': - checklist_item.last_checked_on_matchday = Matchday.get_current() - elif checklist_item_checked == 'false': - checklist_item.last_checked_on_matchday = None - checklist_item.save() - return self.render_json_response({'success': True}) - return self.render_json_response({'success': False}) - - -@method_decorator(login_required, name='dispatch') -class DeleteChecklistItemView(CsrfExemptMixin, JsonRequestResponseMixin, View): - def post(self, request, *args, **kwargs): - checklist_item_id = request.POST.get('checklist_item_id') - checklist_item = ChecklistItem.objects.get(checklist__user=request.user, id=checklist_item_id) - if checklist_item: - checklist_item.delete() - return self.render_json_response({'success': True}) - return self.render_json_response({'success': False}) - - -def logout_view(request): - if request.user.is_authenticated(): - logout(request) - messages.success(request, "Du wurdest abgemeldet.") - return redirect('core:home') - - -def account_view(request): - if request.user.is_authenticated(): - return render(request, 'core/account/home.html') - else: - messages.error(request, MSG_NOT_LOGGED_IN) - return redirect('core:login') diff --git a/core/views/checklist_views.py b/core/views/checklist_views.py new file mode 100644 index 0000000..15f323a --- /dev/null +++ b/core/views/checklist_views.py @@ -0,0 +1,158 @@ +from braces.views import CsrfExemptMixin, JsonRequestResponseMixin +from django.contrib.auth.decorators import login_required +from django.utils.decorators import method_decorator +from django.views import View + +from core.models import ChecklistItem, Matchday, Match, Checklist + + +@method_decorator(login_required, name='dispatch') +class GetChecklistItemsView(CsrfExemptMixin, JsonRequestResponseMixin, View): + def get(self, request, *args, **kwargs): + checklist_items = ChecklistItem.objects.filter(checklist__user=request.user) + + checklist_items_json = [_get_checklist_item_in_json(item) for item in checklist_items] + + return self.render_json_response(checklist_items_json) + + +@method_decorator(login_required, name='dispatch') +class GetChecklistItemsForTodayView(CsrfExemptMixin, JsonRequestResponseMixin, View): + def get(self, request, *args, **kwargs): + current_matchday = Matchday.get_current() + home_match_tomorrow = Match.objects.filter( + user=request.user, + matchday__season__number=current_matchday.season.number, + matchday__number=current_matchday.number + 1, + is_home_match=True + ) + checklist_items = ChecklistItem.objects.filter(checklist__user=request.user) + checklist_items_everyday = checklist_items.filter( + to_be_checked_on_matchdays=None, + to_be_checked_on_matchday_pattern=None, + to_be_checked_if_home_match_tomorrow=False + ) + filtered_checklist_items = [] + filtered_checklist_items.extend(checklist_items_everyday) + checklist_items_this_matchday = checklist_items.filter( + to_be_checked_on_matchdays__isnull=False, + to_be_checked_on_matchday_pattern=None, + to_be_checked_if_home_match_tomorrow=False + ) + filtered_checklist_items.extend([c for c in checklist_items_this_matchday if + current_matchday.number in [int(x) for x in + c.to_be_checked_on_matchdays.split(',')]]) + if home_match_tomorrow: + checklist_items_home_match = checklist_items.filter( + to_be_checked_on_matchdays=None, + to_be_checked_on_matchday_pattern=None, + to_be_checked_if_home_match_tomorrow=True + ) + filtered_checklist_items.extend(checklist_items_home_match) + if current_matchday.number > 0: + checklist_items_matchday_pattern_pre = checklist_items.filter( + to_be_checked_on_matchdays=None, + to_be_checked_on_matchday_pattern__isnull=False, + to_be_checked_if_home_match_tomorrow=False + ) + checklist_items_matchday_pattern = [c for c + in checklist_items_matchday_pattern_pre + if current_matchday.number % c.to_be_checked_on_matchday_pattern == 0] + filtered_checklist_items.extend(checklist_items_matchday_pattern) + + sorted_checklist_items = sorted(filtered_checklist_items, key=lambda x: x.priority, reverse=False) + checklist_items_json = [_get_checklist_item_in_json(item) for item in sorted_checklist_items] + + return self.render_json_response(checklist_items_json) + + +def _get_checklist_item_in_json(checklist_item): + checklist_item_json = dict() + checklist_item_json['id'] = checklist_item.id + checklist_item_json['name'] = checklist_item.name + if checklist_item.to_be_checked_if_home_match_tomorrow: + checklist_item_json['type_home_match'] = checklist_item.to_be_checked_if_home_match_tomorrow + if checklist_item.to_be_checked_on_matchdays is not None: + checklist_item_json['type_matchdays'] = checklist_item.to_be_checked_on_matchdays + if checklist_item.to_be_checked_on_matchday_pattern is not None: + checklist_item_json['type_matchday_pattern'] = checklist_item.to_be_checked_on_matchday_pattern + checklist_item_json['checked'] = checklist_item.last_checked_on_matchday == Matchday.get_current() + + return checklist_item_json + + +@method_decorator(login_required, name='dispatch') +class CreateChecklistItemView(CsrfExemptMixin, JsonRequestResponseMixin, View): + def get(self, request, *args, **kwargs): + checklist, _ = Checklist.objects.get_or_create(user=request.user) + new_checklist_item = ChecklistItem.objects.create(checklist=checklist, name='Neuer Eintrag') + + new_checklist_item_json = _get_checklist_item_in_json(new_checklist_item) + + return self.render_json_response(new_checklist_item_json) + + +@method_decorator(login_required, name='dispatch') +class UpdateChecklistPriorityView(CsrfExemptMixin, JsonRequestResponseMixin, View): + def post(self, request, *args, **kwargs): + checklist_priority = request.POST.get('checklist_priority') + + priority = [int(x) for x in checklist_priority.split(',')] + for checklist_item_id in priority: + checklist_item = ChecklistItem.objects.get(checklist__user=request.user, id=checklist_item_id) + checklist_item.priority = priority.index(checklist_item_id) + checklist_item.save() + + return self.render_json_response({'success': True}) + + +@method_decorator(login_required, name='dispatch') +class UpdateChecklistItemView(CsrfExemptMixin, JsonRequestResponseMixin, View): + def post(self, request, *args, **kwargs): + checklist_item_id = request.POST.get('checklist_item_id') + checklist_item_name = request.POST.get('checklist_item_name') + checklist_item_matchdays = request.POST.get('checklist_item_matchdays') + checklist_item_matchday_pattern = request.POST.get('checklist_item_matchday_pattern') + checklist_item_home_match = request.POST.get('checklist_item_home_match') + checklist_item_everyday = request.POST.get('checklist_item_everyday') + checklist_item_checked = request.POST.get('checklist_item_checked') + + checklist_item = ChecklistItem.objects.get(checklist__user=request.user, id=checklist_item_id) + + if checklist_item: + if checklist_item_name: + checklist_item.name = checklist_item_name + elif checklist_item_matchdays: + checklist_item.to_be_checked_on_matchdays = checklist_item_matchdays + checklist_item.to_be_checked_on_matchday_pattern = None + checklist_item.to_be_checked_if_home_match_tomorrow = False + elif checklist_item_matchday_pattern: + checklist_item.to_be_checked_on_matchdays = None + checklist_item.to_be_checked_on_matchday_pattern = checklist_item_matchday_pattern + checklist_item.to_be_checked_if_home_match_tomorrow = False + elif checklist_item_home_match: + checklist_item.to_be_checked_on_matchdays = None + checklist_item.to_be_checked_on_matchday_pattern = None + checklist_item.to_be_checked_if_home_match_tomorrow = True + elif checklist_item_everyday: + checklist_item.to_be_checked_on_matchdays = None + checklist_item.to_be_checked_on_matchday_pattern = None + checklist_item.to_be_checked_if_home_match_tomorrow = False + elif checklist_item_checked == 'true': + checklist_item.last_checked_on_matchday = Matchday.get_current() + elif checklist_item_checked == 'false': + checklist_item.last_checked_on_matchday = None + checklist_item.save() + return self.render_json_response({'success': True}) + return self.render_json_response({'success': False}) + + +@method_decorator(login_required, name='dispatch') +class DeleteChecklistItemView(CsrfExemptMixin, JsonRequestResponseMixin, View): + def post(self, request, *args, **kwargs): + checklist_item_id = request.POST.get('checklist_item_id') + checklist_item = ChecklistItem.objects.get(checklist__user=request.user, id=checklist_item_id) + if checklist_item: + checklist_item.delete() + return self.render_json_response({'success': True}) + return self.render_json_response({'success': False}) diff --git a/core/localizations/__init__.py b/core/views/ofm/__init__.py similarity index 100% rename from core/localizations/__init__.py rename to core/views/ofm/__init__.py diff --git a/core/views/finance_views.py b/core/views/ofm/finance_views.py similarity index 100% rename from core/views/finance_views.py rename to core/views/ofm/finance_views.py diff --git a/core/views/match_views.py b/core/views/ofm/match_views.py similarity index 100% rename from core/views/match_views.py rename to core/views/ofm/match_views.py diff --git a/core/views/player_views.py b/core/views/ofm/player_views.py similarity index 100% rename from core/views/player_views.py rename to core/views/ofm/player_views.py diff --git a/core/views/stadium_views.py b/core/views/ofm/stadium_views.py similarity index 100% rename from core/views/stadium_views.py rename to core/views/ofm/stadium_views.py diff --git a/core/views/settings_views.py b/core/views/settings_views.py new file mode 100644 index 0000000..7dc34e4 --- /dev/null +++ b/core/views/settings_views.py @@ -0,0 +1,53 @@ +from django.contrib import messages +from django.shortcuts import redirect, render + +from core.localization.messages import MSG_PASSWORDS_UNEQUAL, MSG_SETTINGS_SAVED, MSG_OFM_PASSWORDS_UNEQUAL, \ + MSG_NOT_LOGGED_IN +from users.models import OFMUser + + +def _handle_account_data_change(request, email, password, password2): + if email: + if OFMUser.objects.filter(email=email).exclude(id=request.user.id).exists(): + messages.error(request, "Ein anderer Account existiert bereits mit dieser E-Mail-Adresse.") + return + request.user.email = email + if password and password2: + if password != password2: + messages.error(request, MSG_PASSWORDS_UNEQUAL) + return + request.user.set_password(password) + request.user.save() + messages.success(request, MSG_SETTINGS_SAVED) + + +def _handle_ofm_data_change(request, ofm_password, ofm_password2): + if ofm_password != ofm_password2: + messages.error(request, MSG_OFM_PASSWORDS_UNEQUAL) + return redirect('core:register') + + request.user.ofm_password = ofm_password + request.user.save() + messages.success(request, MSG_SETTINGS_SAVED) + + +def settings_view(request): + if request.user.is_authenticated(): + if request.POST: + email = request.POST.get('email') + password = request.POST.get('password') + password2 = request.POST.get('password2') + ofm_password = request.POST.get('ofm_password') + ofm_password2 = request.POST.get('ofm_password2') + + if email or (password and password2): + _handle_account_data_change(request, email, password, password2) + elif ofm_password and ofm_password2: + _handle_ofm_data_change(request, ofm_password, ofm_password2) + else: + messages.error(request, "Die Daten waren nicht vollständig. Bitte überprüfe die Eingabe.") + + return render(request, 'core/account/settings.html') + else: + messages.error(request, MSG_NOT_LOGGED_IN) + return redirect('core:login') diff --git a/core/views/trigger_parsing_views.py b/core/views/trigger_parsing_views.py index 115aeb4..dc67c60 100644 --- a/core/views/trigger_parsing_views.py +++ b/core/views/trigger_parsing_views.py @@ -1,7 +1,7 @@ from django.contrib import messages from django.shortcuts import redirect -from core.localizations.messages import MSG_NOT_LOGGED_IN +from core.localization.messages import MSG_NOT_LOGGED_IN, NEWER_OFM_VERSION_AVAILABLE from core.managers.parser_manager import ParserManager from core.managers.site_manager import SiteManager @@ -19,8 +19,7 @@ def trigger_parsing(request): with open('version', 'r') as version_file: own_version = version_file.read().replace('\n', '') if own_version != "null" and own_version != remote_version: - messages.info(request, "Es ist eine neuere Version von OFM Helper verfügbar: %s. Du nutzt noch: %s." % ( - remote_version, own_version)) + messages.info(request, NEWER_OFM_VERSION_AVAILABLE % (remote_version, own_version)) except IOError: pass From 5a07de5ead993372e0492b553e77e90fc106f473 Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Sat, 10 Dec 2016 21:53:38 +0100 Subject: [PATCH 31/71] #99 fix too long line after refactorings --- core/ofm_urls.py | 7 ++++--- core/urls.py | 24 ++++++++++++++++-------- core/views/base_views.py | 2 -- 3 files changed, 20 insertions(+), 13 deletions(-) diff --git a/core/ofm_urls.py b/core/ofm_urls.py index b46e471..9ee960a 100644 --- a/core/ofm_urls.py +++ b/core/ofm_urls.py @@ -1,11 +1,12 @@ from django.conf.urls import url from core.views.ofm.finance_views import FinanceDataView, FinancesAsJsonView, FinanceBalanceChartView, \ - FinanceIncomeChartView, FinanceExpensesChartView + FinanceIncomeChartView, FinanceExpensesChartView from core.views.ofm.match_views import MatchesView, MatchesAsJsonView, MatchesSummaryJsonView -from core.views.ofm.player_views import PlayerStatisticsView, PlayerStatisticsAsJsonView, PlayerDetailView, PlayerChartView +from core.views.ofm.player_views import PlayerStatisticsView, PlayerStatisticsAsJsonView, \ + PlayerDetailView, PlayerChartView from core.views.ofm.stadium_views import StadiumStatisticsView, StadiumStatisticsAsJsonView, StadiumDetailView, \ - StadiumStandStatisticsView, StadiumStandStatisticsChartView + StadiumStandStatisticsView, StadiumStandStatisticsChartView app_name = 'ofm' urlpatterns = [ diff --git a/core/urls.py b/core/urls.py index 6d52da5..fd9a87b 100644 --- a/core/urls.py +++ b/core/urls.py @@ -19,11 +19,14 @@ url(r'^ofm/', include('core.ofm_urls'), name='ofm'), url(r'^get_current_matchday/?$', GetCurrentMatchdayView.as_view(), name='get_current_matchday'), - url(r'^settings/?$', core.views.settings_views.settings_view, name='settings'), - url(r'^settings_get_checklist_items/?$', GetChecklistItemsView.as_view(), name='settings_get_checklist_items'), + url(r'^settings/?$', core.views.settings_views.settings_view, + name='settings'), + url(r'^settings_get_checklist_items/?$', GetChecklistItemsView.as_view(), + name='settings_get_checklist_items'), url(r'^settings_get_checklist_items_for_today/?$', GetChecklistItemsForTodayView.as_view(), name='settings_get_checklist_items_for_today'), - url(r'^settings_add_checklist_item/?$', CreateChecklistItemView.as_view(), name='settings_add_checklist_item'), + url(r'^settings_add_checklist_item/?$', CreateChecklistItemView.as_view(), + name='settings_add_checklist_item'), url(r'^settings_update_checklist_item/?$', UpdateChecklistItemView.as_view(), name='settings_update_checklist_item'), url(r'^settings_delete_checklist_item/?$', DeleteChecklistItemView.as_view(), @@ -31,11 +34,16 @@ url(r'^settings_update_checklist_priority/?$', UpdateChecklistPriorityView.as_view(), name='settings_update_checklist_priority'), - url(r'^trigger_parsing/?$', core.views.trigger_parsing_views.trigger_parsing, name='trigger_parsing'), - url(r'^trigger_matchday_parsing/?$', core.views.trigger_parsing_views.trigger_matchday_parsing, name='trigger_matchday_parsing'), - url(r'^trigger_players_parsing/?$', core.views.trigger_parsing_views.trigger_players_parsing, name='trigger_players_parsing'), + url(r'^trigger_parsing/?$', core.views.trigger_parsing_views.trigger_parsing, + name='trigger_parsing'), + url(r'^trigger_matchday_parsing/?$', core.views.trigger_parsing_views.trigger_matchday_parsing, + name='trigger_matchday_parsing'), + url(r'^trigger_players_parsing/?$', core.views.trigger_parsing_views.trigger_players_parsing, + name='trigger_players_parsing'), url(r'^trigger_player_statistics_parsing/?$', core.views.trigger_parsing_views.trigger_player_statistics_parsing, name='trigger_player_statistics_parsing'), - url(r'^trigger_finances_parsing/?$', core.views.trigger_parsing_views.trigger_finances_parsing, name='trigger_finances_parsing'), - url(r'^trigger_match_parsing/?$', core.views.trigger_parsing_views.trigger_match_parsing, name='trigger_match_parsing'), + url(r'^trigger_finances_parsing/?$', core.views.trigger_parsing_views.trigger_finances_parsing, + name='trigger_finances_parsing'), + url(r'^trigger_match_parsing/?$', core.views.trigger_parsing_views.trigger_match_parsing, + name='trigger_match_parsing'), ] diff --git a/core/views/base_views.py b/core/views/base_views.py index e58bd29..a24a2e7 100644 --- a/core/views/base_views.py +++ b/core/views/base_views.py @@ -14,5 +14,3 @@ def get(self, request, *args, **kwargs): matchday_json['matchday_number'] = current_matchday.number matchday_json['season_number'] = current_matchday.season.number return self.render_json_response(matchday_json) - - From bd66dff8cb61aa245460a47de10418fb26680388 Mon Sep 17 00:00:00 2001 From: Michael Wittig Date: Sun, 11 Dec 2016 10:33:22 +0100 Subject: [PATCH 32/71] #99 extract more strings into localization module --- core/localization/messages.py | 13 +++++++++++-- core/views/account_views.py | 23 +++++++++++++---------- 2 files changed, 24 insertions(+), 12 deletions(-) diff --git a/core/localization/messages.py b/core/localization/messages.py index 90a4019..d8d9597 100644 --- a/core/localization/messages.py +++ b/core/localization/messages.py @@ -1,5 +1,14 @@ +EMAIL_ALREADY_EXISTS = "Ein Account mit dieser E-Mail-Adresse existiert bereits." +MSG_ACCOUNT_CREATED = "Account wurde erstellt. Jetzt kannst du dich einloggen." +MSG_ALREADY_LOGGED_IN = "Du bist bereits eingeloggt. Du kannst dich im Menü ausloggen." MSG_NOT_LOGGED_IN = "Du bist nicht eingeloggt!" -MSG_SETTINGS_SAVED = "Die neuen Einstellungen wurden gespeichert." -MSG_PASSWORDS_UNEQUAL = "Die eingegeben Passwörter stimmen nicht überein." MSG_OFM_PASSWORDS_UNEQUAL = "Die eingegeben OFM Passwörter stimmen nicht überein." +MSG_PASSWORDS_UNEQUAL = "Die eingegeben Passwörter stimmen nicht überein." +MSG_SETTINGS_SAVED = "Die neuen Einstellungen wurden gespeichert." NEWER_OFM_VERSION_AVAILABLE = "Es ist eine neuere Version von OFM Helper verfügbar: %s. Du nutzt noch: %s." +OFM_USERNAME_ALREADY_EXISTS = "Es existiert bereits ein Account für diesen OFM Benutzernamen." +USERNAME_ALREADY_EXISTS = "Ein Account mit diesem Benutzernamen existiert bereits." +LOGGED_OUT = "Du wurdest abgemeldet." +USERNAME_OR_PASSWORD_INVALID = "Benutzername und/oder Passwort nicht korrekt." +LOGIN_IMPOSSIBLE_ACCOUNT_IS_DEACTIVATED = "Login nicht möglich. Dein Account wurde deaktiviert." +LOGIN_SUCCESSFUL = "Login erfolgreich." diff --git a/core/views/account_views.py b/core/views/account_views.py index 6dc3a11..47f65d9 100644 --- a/core/views/account_views.py +++ b/core/views/account_views.py @@ -2,13 +2,16 @@ from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect -from core.localization.messages import MSG_PASSWORDS_UNEQUAL, MSG_OFM_PASSWORDS_UNEQUAL, MSG_NOT_LOGGED_IN +from core.localization.messages import MSG_PASSWORDS_UNEQUAL, MSG_OFM_PASSWORDS_UNEQUAL, MSG_NOT_LOGGED_IN, \ + OFM_USERNAME_ALREADY_EXISTS, USERNAME_ALREADY_EXISTS, EMAIL_ALREADY_EXISTS, MSG_ALREADY_LOGGED_IN, \ + MSG_ACCOUNT_CREATED, LOGGED_OUT, USERNAME_OR_PASSWORD_INVALID, LOGIN_IMPOSSIBLE_ACCOUNT_IS_DEACTIVATED, \ + LOGIN_SUCCESSFUL from users.models import OFMUser def register_view(request): if request.user.is_authenticated(): - messages.error(request, "Du bist bereits eingeloggt. Du kannst dich im Menü ausloggen.") + messages.error(request, MSG_ALREADY_LOGGED_IN) return render(request, 'core/account/home.html') if request.POST: username = request.POST.get('username') @@ -20,11 +23,11 @@ def register_view(request): ofm_password2 = request.POST.get('ofm_password2') if OFMUser.objects.filter(email=email).exists(): - messages.error(request, "Ein Account mit dieser E-Mail-Adresse existiert bereits.") + messages.error(request, EMAIL_ALREADY_EXISTS) return redirect('core:register') if OFMUser.objects.filter(username=username).exists(): - messages.error(request, "Ein Account mit diesem Benutzernamen existiert bereits.") + messages.error(request, USERNAME_ALREADY_EXISTS) return redirect('core:register') if password != password2: @@ -32,7 +35,7 @@ def register_view(request): return redirect('core:register') if OFMUser.objects.filter(ofm_username=ofm_username).exists(): - messages.error(request, "Es existiert bereits ein Account für diesen OFM Benutzernamen.") + messages.error(request, OFM_USERNAME_ALREADY_EXISTS) return redirect('core:register') if ofm_password != ofm_password2: @@ -47,7 +50,7 @@ def register_view(request): ofm_password=ofm_password, ) - messages.success(request, "Account wurde erstellt. Jetzt kannst du dich einloggen.") + messages.success(request, MSG_ACCOUNT_CREATED) return redirect('core:login') else: @@ -62,13 +65,13 @@ def login_view(request): if user is not None: if user.is_active: login(request, user) - messages.success(request, "Login erfolgreich.") + messages.success(request, LOGIN_SUCCESSFUL) return render(request, 'core/account/home.html') else: - messages.error(request, "Login nicht möglich. Dein Account wurde deaktiviert.") + messages.error(request, LOGIN_IMPOSSIBLE_ACCOUNT_IS_DEACTIVATED) return redirect('core:login') else: - messages.error(request, "Benutzername und/oder Passwort nicht korrekt.") + messages.error(request, USERNAME_OR_PASSWORD_INVALID) return redirect('core:login') else: if request.user.is_authenticated(): @@ -80,7 +83,7 @@ def login_view(request): def logout_view(request): if request.user.is_authenticated(): logout(request) - messages.success(request, "Du wurdest abgemeldet.") + messages.success(request, LOGGED_OUT) return redirect('core:home') From 7c6e8601f8abf852cf324439bf00045265f0dd64 Mon Sep 17 00:00:00 2001 From: "sebastian.schreck" Date: Sun, 11 Dec 2016 12:09:06 +0100 Subject: [PATCH 33/71] renamed localization messages and ordered them alphabetically --- core/localization/messages.py | 18 +++++++++--------- core/views/account_views.py | 16 ++++++++-------- core/views/settings_views.py | 14 +++++++------- core/views/trigger_parsing_views.py | 6 +++--- 4 files changed, 27 insertions(+), 27 deletions(-) diff --git a/core/localization/messages.py b/core/localization/messages.py index d8d9597..e673b86 100644 --- a/core/localization/messages.py +++ b/core/localization/messages.py @@ -1,14 +1,14 @@ +ACCOUNT_CREATED = "Account wurde erstellt. Jetzt kannst du dich einloggen." +ALREADY_LOGGED_IN = "Du bist bereits eingeloggt. Du kannst dich im Menü ausloggen." EMAIL_ALREADY_EXISTS = "Ein Account mit dieser E-Mail-Adresse existiert bereits." -MSG_ACCOUNT_CREATED = "Account wurde erstellt. Jetzt kannst du dich einloggen." -MSG_ALREADY_LOGGED_IN = "Du bist bereits eingeloggt. Du kannst dich im Menü ausloggen." -MSG_NOT_LOGGED_IN = "Du bist nicht eingeloggt!" -MSG_OFM_PASSWORDS_UNEQUAL = "Die eingegeben OFM Passwörter stimmen nicht überein." -MSG_PASSWORDS_UNEQUAL = "Die eingegeben Passwörter stimmen nicht überein." -MSG_SETTINGS_SAVED = "Die neuen Einstellungen wurden gespeichert." +LOGGED_OUT = "Du wurdest abgemeldet." +LOGIN_IMPOSSIBLE_ACCOUNT_IS_DEACTIVATED = "Login nicht möglich. Dein Account wurde deaktiviert." +LOGIN_SUCCESSFUL = "Login erfolgreich." NEWER_OFM_VERSION_AVAILABLE = "Es ist eine neuere Version von OFM Helper verfügbar: %s. Du nutzt noch: %s." +NOT_LOGGED_IN = "Du bist nicht eingeloggt!" +OFM_PASSWORDS_UNEQUAL = "Die eingegeben OFM Passwörter stimmen nicht überein." OFM_USERNAME_ALREADY_EXISTS = "Es existiert bereits ein Account für diesen OFM Benutzernamen." +PASSWORDS_UNEQUAL = "Die eingegeben Passwörter stimmen nicht überein." +SETTINGS_SAVED = "Die neuen Einstellungen wurden gespeichert." USERNAME_ALREADY_EXISTS = "Ein Account mit diesem Benutzernamen existiert bereits." -LOGGED_OUT = "Du wurdest abgemeldet." USERNAME_OR_PASSWORD_INVALID = "Benutzername und/oder Passwort nicht korrekt." -LOGIN_IMPOSSIBLE_ACCOUNT_IS_DEACTIVATED = "Login nicht möglich. Dein Account wurde deaktiviert." -LOGIN_SUCCESSFUL = "Login erfolgreich." diff --git a/core/views/account_views.py b/core/views/account_views.py index 47f65d9..76d294b 100644 --- a/core/views/account_views.py +++ b/core/views/account_views.py @@ -2,16 +2,16 @@ from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect -from core.localization.messages import MSG_PASSWORDS_UNEQUAL, MSG_OFM_PASSWORDS_UNEQUAL, MSG_NOT_LOGGED_IN, \ - OFM_USERNAME_ALREADY_EXISTS, USERNAME_ALREADY_EXISTS, EMAIL_ALREADY_EXISTS, MSG_ALREADY_LOGGED_IN, \ - MSG_ACCOUNT_CREATED, LOGGED_OUT, USERNAME_OR_PASSWORD_INVALID, LOGIN_IMPOSSIBLE_ACCOUNT_IS_DEACTIVATED, \ +from core.localization.messages import PASSWORDS_UNEQUAL, OFM_PASSWORDS_UNEQUAL, NOT_LOGGED_IN, \ + OFM_USERNAME_ALREADY_EXISTS, USERNAME_ALREADY_EXISTS, EMAIL_ALREADY_EXISTS, ALREADY_LOGGED_IN, \ + ACCOUNT_CREATED, LOGGED_OUT, USERNAME_OR_PASSWORD_INVALID, LOGIN_IMPOSSIBLE_ACCOUNT_IS_DEACTIVATED, \ LOGIN_SUCCESSFUL from users.models import OFMUser def register_view(request): if request.user.is_authenticated(): - messages.error(request, MSG_ALREADY_LOGGED_IN) + messages.error(request, ALREADY_LOGGED_IN) return render(request, 'core/account/home.html') if request.POST: username = request.POST.get('username') @@ -31,7 +31,7 @@ def register_view(request): return redirect('core:register') if password != password2: - messages.error(request, MSG_PASSWORDS_UNEQUAL) + messages.error(request, PASSWORDS_UNEQUAL) return redirect('core:register') if OFMUser.objects.filter(ofm_username=ofm_username).exists(): @@ -39,7 +39,7 @@ def register_view(request): return redirect('core:register') if ofm_password != ofm_password2: - messages.error(request, MSG_OFM_PASSWORDS_UNEQUAL) + messages.error(request, OFM_PASSWORDS_UNEQUAL) return redirect('core:register') OFMUser.objects.create_user( @@ -50,7 +50,7 @@ def register_view(request): ofm_password=ofm_password, ) - messages.success(request, MSG_ACCOUNT_CREATED) + messages.success(request, ACCOUNT_CREATED) return redirect('core:login') else: @@ -91,5 +91,5 @@ def account_view(request): if request.user.is_authenticated(): return render(request, 'core/account/home.html') else: - messages.error(request, MSG_NOT_LOGGED_IN) + messages.error(request, NOT_LOGGED_IN) return redirect('core:login') diff --git a/core/views/settings_views.py b/core/views/settings_views.py index 7dc34e4..43b9663 100644 --- a/core/views/settings_views.py +++ b/core/views/settings_views.py @@ -1,8 +1,8 @@ from django.contrib import messages from django.shortcuts import redirect, render -from core.localization.messages import MSG_PASSWORDS_UNEQUAL, MSG_SETTINGS_SAVED, MSG_OFM_PASSWORDS_UNEQUAL, \ - MSG_NOT_LOGGED_IN +from core.localization.messages import PASSWORDS_UNEQUAL, SETTINGS_SAVED, OFM_PASSWORDS_UNEQUAL, \ + NOT_LOGGED_IN from users.models import OFMUser @@ -14,21 +14,21 @@ def _handle_account_data_change(request, email, password, password2): request.user.email = email if password and password2: if password != password2: - messages.error(request, MSG_PASSWORDS_UNEQUAL) + messages.error(request, PASSWORDS_UNEQUAL) return request.user.set_password(password) request.user.save() - messages.success(request, MSG_SETTINGS_SAVED) + messages.success(request, SETTINGS_SAVED) def _handle_ofm_data_change(request, ofm_password, ofm_password2): if ofm_password != ofm_password2: - messages.error(request, MSG_OFM_PASSWORDS_UNEQUAL) + messages.error(request, OFM_PASSWORDS_UNEQUAL) return redirect('core:register') request.user.ofm_password = ofm_password request.user.save() - messages.success(request, MSG_SETTINGS_SAVED) + messages.success(request, SETTINGS_SAVED) def settings_view(request): @@ -49,5 +49,5 @@ def settings_view(request): return render(request, 'core/account/settings.html') else: - messages.error(request, MSG_NOT_LOGGED_IN) + messages.error(request, NOT_LOGGED_IN) return redirect('core:login') diff --git a/core/views/trigger_parsing_views.py b/core/views/trigger_parsing_views.py index dc67c60..bbfed9e 100644 --- a/core/views/trigger_parsing_views.py +++ b/core/views/trigger_parsing_views.py @@ -1,7 +1,7 @@ from django.contrib import messages from django.shortcuts import redirect -from core.localization.messages import MSG_NOT_LOGGED_IN, NEWER_OFM_VERSION_AVAILABLE +from core.localization.messages import NOT_LOGGED_IN, NEWER_OFM_VERSION_AVAILABLE from core.managers.parser_manager import ParserManager from core.managers.site_manager import SiteManager @@ -27,7 +27,7 @@ def trigger_parsing(request): return redirect('core:ofm:player_statistics') else: - messages.error(request, MSG_NOT_LOGGED_IN) + messages.error(request, NOT_LOGGED_IN) return redirect('core:login') @@ -38,7 +38,7 @@ def trigger_single_parsing(request, parsing_function, redirect_to='core:account' parsing_function(request, site_manager) return redirect(redirect_to) else: - messages.error(request, MSG_NOT_LOGGED_IN) + messages.error(request, NOT_LOGGED_IN) return redirect('core:login') From 88d9226daaf1d101497cc577633d18d1a625dcab Mon Sep 17 00:00:00 2001 From: "sebastian.schreck" Date: Sun, 11 Dec 2016 12:49:03 +0100 Subject: [PATCH 34/71] moved get_current_matchday url to ofm --- core/ofm_urls.py | 17 ++++++++++------- core/static/core/js/checklist_user_handler.js | 2 +- core/tests/unit/views/test_settings_view.py | 2 +- core/urls.py | 11 +++++------ core/views/{ => ofm}/base_views.py | 0 5 files changed, 17 insertions(+), 15 deletions(-) rename core/views/{ => ofm}/base_views.py (100%) diff --git a/core/ofm_urls.py b/core/ofm_urls.py index 9ee960a..e97101b 100644 --- a/core/ofm_urls.py +++ b/core/ofm_urls.py @@ -1,12 +1,13 @@ from django.conf.urls import url -from core.views.ofm.finance_views import FinanceDataView, FinancesAsJsonView, FinanceBalanceChartView, \ - FinanceIncomeChartView, FinanceExpensesChartView -from core.views.ofm.match_views import MatchesView, MatchesAsJsonView, MatchesSummaryJsonView -from core.views.ofm.player_views import PlayerStatisticsView, PlayerStatisticsAsJsonView, \ - PlayerDetailView, PlayerChartView -from core.views.ofm.stadium_views import StadiumStatisticsView, StadiumStatisticsAsJsonView, StadiumDetailView, \ - StadiumStandStatisticsView, StadiumStandStatisticsChartView +from core.views.ofm.base_views import GetCurrentMatchdayView +from core.views.ofm.finance_views import FinanceBalanceChartView, FinanceDataView, FinanceExpensesChartView, \ + FinanceIncomeChartView, FinancesAsJsonView +from core.views.ofm.match_views import MatchesAsJsonView, MatchesSummaryJsonView, MatchesView +from core.views.ofm.player_views import PlayerChartView, PlayerDetailView, PlayerStatisticsAsJsonView, \ + PlayerStatisticsView +from core.views.ofm.stadium_views import StadiumDetailView, StadiumStandStatisticsChartView, StadiumStandStatisticsView, \ + StadiumStatisticsAsJsonView, StadiumStatisticsView app_name = 'ofm' urlpatterns = [ @@ -31,4 +32,6 @@ url(r'^stadium_stand/?$', StadiumStandStatisticsView.as_view(), name='stadium_stand_statistics'), url(r'^stadium_stand_chart_json/?$', StadiumStandStatisticsChartView.as_view(), name='stadium_stand_statistics_chart_json'), + + url(r'^get_current_matchday/?$', GetCurrentMatchdayView.as_view(), name='get_current_matchday'), ] diff --git a/core/static/core/js/checklist_user_handler.js b/core/static/core/js/checklist_user_handler.js index d5385bc..39f2d03 100644 --- a/core/static/core/js/checklist_user_handler.js +++ b/core/static/core/js/checklist_user_handler.js @@ -21,7 +21,7 @@ $('document').ready( function (){ data.forEach(showChecklistItem); } ); - $.get("/get_current_matchday", + $.get("/ofm/get_current_matchday", function (data) { $('#ChecklistBar').find('a').append( "" + diff --git a/core/tests/unit/views/test_settings_view.py b/core/tests/unit/views/test_settings_view.py index 7014a2b..917bb45 100644 --- a/core/tests/unit/views/test_settings_view.py +++ b/core/tests/unit/views/test_settings_view.py @@ -96,7 +96,7 @@ def test_change_password_when_unmatching(self): def test_get_current_matchday(self): MatchdayFactory.create() self.client.login(username='temporary', password='temporary') - response = self.client.get(reverse('core:get_current_matchday')) + response = self.client.get(reverse('core:ofm:get_current_matchday')) self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) self.assertEqual(returned_json_data['matchday_number'], 0) diff --git a/core/urls.py b/core/urls.py index fd9a87b..90f1818 100644 --- a/core/urls.py +++ b/core/urls.py @@ -1,12 +1,12 @@ -from django.conf.urls import url, include -from django.views.generic.base import TemplateView, RedirectView +from django.conf.urls import include, url +from django.views.generic.base import RedirectView, TemplateView import core.views.account_views import core.views.settings_views import core.views.trigger_parsing_views -from core.views.base_views import GetCurrentMatchdayView -from core.views.checklist_views import GetChecklistItemsView, GetChecklistItemsForTodayView, CreateChecklistItemView, \ - UpdateChecklistPriorityView, UpdateChecklistItemView, DeleteChecklistItemView +from core.views.checklist_views import CreateChecklistItemView, DeleteChecklistItemView, \ + GetChecklistItemsForTodayView, GetChecklistItemsView, \ + UpdateChecklistItemView, UpdateChecklistPriorityView app_name = 'core' urlpatterns = [ @@ -17,7 +17,6 @@ url(r'^account/?$', core.views.account_views.account_view, name='account'), url(r'^logout/?$', core.views.account_views.logout_view, name='logout'), url(r'^ofm/', include('core.ofm_urls'), name='ofm'), - url(r'^get_current_matchday/?$', GetCurrentMatchdayView.as_view(), name='get_current_matchday'), url(r'^settings/?$', core.views.settings_views.settings_view, name='settings'), diff --git a/core/views/base_views.py b/core/views/ofm/base_views.py similarity index 100% rename from core/views/base_views.py rename to core/views/ofm/base_views.py From c992151aae7ef51b47e371d547f807054386ad8c Mon Sep 17 00:00:00 2001 From: "sebastian.schreck" Date: Sun, 11 Dec 2016 13:11:48 +0100 Subject: [PATCH 35/71] fiyed one import line too long --- core/ofm_urls.py | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/core/ofm_urls.py b/core/ofm_urls.py index e97101b..a9189a7 100644 --- a/core/ofm_urls.py +++ b/core/ofm_urls.py @@ -6,8 +6,8 @@ from core.views.ofm.match_views import MatchesAsJsonView, MatchesSummaryJsonView, MatchesView from core.views.ofm.player_views import PlayerChartView, PlayerDetailView, PlayerStatisticsAsJsonView, \ PlayerStatisticsView -from core.views.ofm.stadium_views import StadiumDetailView, StadiumStandStatisticsChartView, StadiumStandStatisticsView, \ - StadiumStatisticsAsJsonView, StadiumStatisticsView +from core.views.ofm.stadium_views import StadiumDetailView, StadiumStandStatisticsChartView, \ + StadiumStandStatisticsView, StadiumStatisticsAsJsonView, StadiumStatisticsView app_name = 'ofm' urlpatterns = [ From 7d3d97ac7a288ec64e0eefe687388ee9d31fd21b Mon Sep 17 00:00:00 2001 From: "sebastian.schreck" Date: Sun, 11 Dec 2016 20:33:39 +0100 Subject: [PATCH 36/71] #99 splitted out checklist urls --- core/checklist_urls.py | 21 +++++++++ .../core/js/checklist_settings_handler.js | 16 +++---- core/static/core/js/checklist_user_handler.js | 4 +- .../views/test_checklist_settings_view.py | 44 +++++++++---------- core/urls.py | 18 ++------ 5 files changed, 56 insertions(+), 47 deletions(-) create mode 100644 core/checklist_urls.py diff --git a/core/checklist_urls.py b/core/checklist_urls.py new file mode 100644 index 0000000..2cc1ce8 --- /dev/null +++ b/core/checklist_urls.py @@ -0,0 +1,21 @@ +from django.conf.urls import url + +from core.views.checklist_views import CreateChecklistItemView, DeleteChecklistItemView, \ + GetChecklistItemsForTodayView, GetChecklistItemsView, \ + UpdateChecklistItemView, UpdateChecklistPriorityView + +app_name = 'checklist' +urlpatterns = [ + url(r'^get_checklist_items/?$', GetChecklistItemsView.as_view(), + name='get_checklist_items'), + url(r'^get_checklist_items_for_today/?$', GetChecklistItemsForTodayView.as_view(), + name='get_checklist_items_for_today'), + url(r'^add_checklist_item/?$', CreateChecklistItemView.as_view(), + name='add_checklist_item'), + url(r'^update_checklist_item/?$', UpdateChecklistItemView.as_view(), + name='update_checklist_item'), + url(r'^delete_checklist_item/?$', DeleteChecklistItemView.as_view(), + name='delete_checklist_item'), + url(r'^update_checklist_priority/?$', UpdateChecklistPriorityView.as_view(), + name='update_checklist_priority'), +] diff --git a/core/static/core/js/checklist_settings_handler.js b/core/static/core/js/checklist_settings_handler.js index 7564d88..16c21a1 100644 --- a/core/static/core/js/checklist_settings_handler.js +++ b/core/static/core/js/checklist_settings_handler.js @@ -58,7 +58,7 @@ $('document').ready( function (){ $('#headingChecklistSettings').click(function(){ if (! $('#collapseChecklistSettings').hasClass('in')) { // area is being opened - $.get("/settings_get_checklist_items", + $.get("/checklist/get_checklist_items", function (data) { $('#checklist_items').html(''); data.forEach(addChecklistItem); @@ -70,7 +70,7 @@ $('document').ready( function (){ $('#add_checklist_item').click( function(event) { event.stopPropagation(); event.preventDefault(); - $.get("/settings_add_checklist_item", + $.get("/checklist/add_checklist_item", function (data) { addChecklistItem(data); } @@ -81,7 +81,7 @@ $('document').ready( function (){ var params = { checklist_priority: $('#checklist_items').sortable("toArray").join(",") }; - $.post("/settings_update_checklist_priority", params); + $.post("/checklist/update_checklist_priority", params); $('#checklist_items_priority_saved').removeClass('invisible'); setTimeout(function() { $('#checklist_items_priority_saved').addClass('invisible'); @@ -93,7 +93,7 @@ $('document').ready( function (){ checklist_item_id: elem.closest('.checklist_item_container').attr('id'), checklist_item_name: elem.val() }; - $.post("/settings_update_checklist_item", params); + $.post("/checklist/update_checklist_item", params); elem.closest('.checklist_item_container').find('.checklist_item_saved').removeClass('invisible'); } $('#checklist_items').on('focusout', '.checklist_item_name', function() { @@ -126,7 +126,7 @@ $('document').ready( function (){ checklist_item_id: elem.closest('.checklist_item_container').attr('id'), checklist_item_matchdays: matchdays_comma_seperated }; - $.post("/settings_update_checklist_item", params); + $.post("/checklist/update_checklist_item", params); elem.closest('.checklist_item_container').find('.checklist_item_saved').removeClass('invisible'); } $('#checklist_items').on('focusout', '.checklist_item_matchdays', function() { @@ -157,7 +157,7 @@ $('document').ready( function (){ checklist_item_id: elem.closest('.checklist_item_container').attr('id'), checklist_item_matchday_pattern: matchday_pattern }; - $.post("/settings_update_checklist_item", params); + $.post("/checklist/update_checklist_item", params); elem.closest('.checklist_item_container').find('.checklist_item_saved').removeClass('invisible'); } $('#checklist_items').on('focusout', '.checklist_item_matchday_pattern', function() { @@ -180,7 +180,7 @@ $('document').ready( function (){ var params = { checklist_item_id: checklist_item.attr('id') }; - $.post("/settings_delete_checklist_item", params); + $.post("/checklist/delete_checklist_item", params); checklist_item.animate({opacity:0, height:0}, 200); setTimeout(function() { checklist_item.remove(); @@ -220,7 +220,7 @@ $('document').ready( function (){ params['checklist_item_everyday'] = true; } - $.post("/settings_update_checklist_item", params); + $.post("/checklist/update_checklist_item", params); }); diff --git a/core/static/core/js/checklist_user_handler.js b/core/static/core/js/checklist_user_handler.js index 39f2d03..752cca8 100644 --- a/core/static/core/js/checklist_user_handler.js +++ b/core/static/core/js/checklist_user_handler.js @@ -15,7 +15,7 @@ function showChecklistItem(item) { $('document').ready( function (){ $(function() { - $.get("/settings_get_checklist_items_for_today", + $.get("/checklist/get_checklist_items_for_today", function (data) { $('#ChecklistSubMenu').html(''); data.forEach(showChecklistItem); @@ -52,7 +52,7 @@ $('document').ready( function (){ checklist_item_id: $(this).attr('id'), checklist_item_checked: checklistItemGotChecked }; - $.post("/settings_update_checklist_item", params); + $.post("/checklist/update_checklist_item", params); if (checklistItemGotChecked) { checklistItem.removeClass('glyphicon-unchecked'); diff --git a/core/tests/unit/views/test_checklist_settings_view.py b/core/tests/unit/views/test_checklist_settings_view.py index f4f4f2f..a7c677d 100644 --- a/core/tests/unit/views/test_checklist_settings_view.py +++ b/core/tests/unit/views/test_checklist_settings_view.py @@ -33,7 +33,7 @@ def setUp(self): def test_get_checklist_items(self): self.client.login(username='temporary', password='temporary') - response = self.client.get(reverse('core:settings_get_checklist_items')) + response = self.client.get(reverse('core:checklist:get_checklist_items')) self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) self.assertEqual(len(returned_json_data), 1) @@ -45,7 +45,7 @@ def test_get_checklist_items(self): def test_create_standard_checklist_item(self): self.client.login(username='second', password='second') - response = self.client.get(reverse('core:settings_add_checklist_item')) + response = self.client.get(reverse('core:checklist:add_checklist_item')) self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) self.assertTrue('id' in returned_json_data) @@ -57,13 +57,13 @@ def test_create_standard_checklist_item(self): def test_update_checklist_item_name(self): self.client.login(username='temporary', password='temporary') - response = self.client.post(reverse('core:settings_update_checklist_item'), + response = self.client.post(reverse('core:checklist:update_checklist_item'), {'checklist_item_id': self.checklist_item.id, 'checklist_item_name': 'do even more unit tests' }) self.assertEqual(response.status_code, 200) - response = self.client.get(reverse('core:settings_get_checklist_items')) + response = self.client.get(reverse('core:checklist:get_checklist_items')) self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) self.assertTrue('id' in returned_json_data[0]) @@ -73,13 +73,13 @@ def test_update_checklist_item_name(self): def test_update_checklist_item_home_match(self): self.client.login(username='temporary', password='temporary') - response = self.client.post(reverse('core:settings_update_checklist_item'), + response = self.client.post(reverse('core:checklist:update_checklist_item'), {'checklist_item_id': self.checklist_item.id, 'checklist_item_home_match': True }) self.assertEqual(response.status_code, 200) - response = self.client.get(reverse('core:settings_get_checklist_items')) + response = self.client.get(reverse('core:checklist:get_checklist_items')) self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) self.assertTrue('id' in returned_json_data[0]) @@ -95,13 +95,13 @@ def test_update_checklist_item_home_match(self): def test_update_checklist_item_matchday(self): self.client.login(username='temporary', password='temporary') - response = self.client.post(reverse('core:settings_update_checklist_item'), + response = self.client.post(reverse('core:checklist:update_checklist_item'), {'checklist_item_id': self.checklist_item.id, 'checklist_item_matchdays': '4' }) self.assertEqual(response.status_code, 200) - response = self.client.get(reverse('core:settings_get_checklist_items')) + response = self.client.get(reverse('core:checklist:get_checklist_items')) self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) self.assertTrue('id' in returned_json_data[0]) @@ -117,13 +117,13 @@ def test_update_checklist_item_matchday(self): def test_update_checklist_item_matchdays(self): self.client.login(username='temporary', password='temporary') - response = self.client.post(reverse('core:settings_update_checklist_item'), + response = self.client.post(reverse('core:checklist:update_checklist_item'), {'checklist_item_id': self.checklist_item.id, 'checklist_item_matchdays': '3,33' }) self.assertEqual(response.status_code, 200) - response = self.client.get(reverse('core:settings_get_checklist_items')) + response = self.client.get(reverse('core:checklist:get_checklist_items')) self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) self.assertTrue('id' in returned_json_data[0]) @@ -139,13 +139,13 @@ def test_update_checklist_item_matchdays(self): def test_update_checklist_item_matchday_pattern(self): self.client.login(username='temporary', password='temporary') - response = self.client.post(reverse('core:settings_update_checklist_item'), + response = self.client.post(reverse('core:checklist:update_checklist_item'), {'checklist_item_id': self.checklist_item.id, 'checklist_item_matchday_pattern': 2 }) self.assertEqual(response.status_code, 200) - response = self.client.get(reverse('core:settings_get_checklist_items')) + response = self.client.get(reverse('core:checklist:get_checklist_items')) self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) self.assertTrue('id' in returned_json_data[0]) @@ -161,13 +161,13 @@ def test_update_checklist_item_matchday_pattern(self): def test_update_checklist_item_everyday(self): self.client.login(username='temporary', password='temporary') - response = self.client.post(reverse('core:settings_update_checklist_item'), + response = self.client.post(reverse('core:checklist:update_checklist_item'), {'checklist_item_id': self.checklist_item.id, 'checklist_item_everyday': True }) self.assertEqual(response.status_code, 200) - response = self.client.get(reverse('core:settings_get_checklist_items')) + response = self.client.get(reverse('core:checklist:get_checklist_items')) self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) self.assertTrue('id' in returned_json_data[0]) @@ -182,14 +182,14 @@ def test_update_checklist_item_everyday(self): def test_update_checklist_item_checked(self): self.client.login(username='temporary', password='temporary') - response = self.client.post(reverse('core:settings_update_checklist_item'), + response = self.client.post(reverse('core:checklist:update_checklist_item'), {'checklist_item_id': self.checklist_item.id, 'checklist_item_checked': 'true' }) self.assertEqual(response.status_code, 200) self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).last_checked_on_matchday, self.matchday) - response = self.client.get(reverse('core:settings_get_checklist_items')) + response = self.client.get(reverse('core:checklist:get_checklist_items')) self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) self.assertTrue('id' in returned_json_data[0]) @@ -199,14 +199,14 @@ def test_update_checklist_item_checked(self): def test_update_checklist_item_unchecked(self): self.client.login(username='temporary', password='temporary') - response = self.client.post(reverse('core:settings_update_checklist_item'), + response = self.client.post(reverse('core:checklist:update_checklist_item'), {'checklist_item_id': self.checklist_item.id, 'checklist_item_checked': 'false' }) self.assertEqual(response.status_code, 200) self.assertEqual(ChecklistItem.objects.get(id=self.checklist_item.id).last_checked_on_matchday, None) - response = self.client.get(reverse('core:settings_get_checklist_items')) + response = self.client.get(reverse('core:checklist:get_checklist_items')) self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) self.assertTrue('id' in returned_json_data[0]) @@ -216,12 +216,12 @@ def test_update_checklist_item_unchecked(self): def test_delete_checklist_item(self): self.client.login(username='temporary', password='temporary') - response = self.client.post(reverse('core:settings_delete_checklist_item'), + response = self.client.post(reverse('core:checklist:delete_checklist_item'), {'checklist_item_id': self.checklist_item.id }) self.assertEqual(response.status_code, 200) - response = self.client.get(reverse('core:settings_get_checklist_items')) + response = self.client.get(reverse('core:checklist:get_checklist_items')) self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) self.assertEqual(len(returned_json_data), 0) @@ -254,7 +254,7 @@ def test_get_checklist_items_for_today(self): to_be_checked_on_matchdays='6,9' ) - response = self.client.get(reverse('core:settings_get_checklist_items_for_today')) + response = self.client.get(reverse('core:checklist:get_checklist_items_for_today')) self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) @@ -292,7 +292,7 @@ def test_get_checklist_items_for_today_if_tomorrow_home_match(self): to_be_checked_if_home_match_tomorrow=True ) - response = self.client.get(reverse('core:settings_get_checklist_items_for_today')) + response = self.client.get(reverse('core:checklist:get_checklist_items_for_today')) self.assertEqual(response.status_code, 200) returned_json_data = json.loads(response.content.decode('utf-8')) diff --git a/core/urls.py b/core/urls.py index 90f1818..70e392c 100644 --- a/core/urls.py +++ b/core/urls.py @@ -4,34 +4,22 @@ import core.views.account_views import core.views.settings_views import core.views.trigger_parsing_views -from core.views.checklist_views import CreateChecklistItemView, DeleteChecklistItemView, \ - GetChecklistItemsForTodayView, GetChecklistItemsView, \ - UpdateChecklistItemView, UpdateChecklistPriorityView app_name = 'core' urlpatterns = [ url(r'^favicon\.ico$', RedirectView.as_view(url='/static/core/img/OFM_favicon.png', permanent=True)), url(r'^$', TemplateView.as_view(template_name='core/home.html'), name='home'), + url(r'^register/?$', core.views.account_views.register_view, name='register'), url(r'^login/?$', core.views.account_views.login_view, name='login'), url(r'^account/?$', core.views.account_views.account_view, name='account'), url(r'^logout/?$', core.views.account_views.logout_view, name='logout'), + url(r'^ofm/', include('core.ofm_urls'), name='ofm'), + url(r'^checklist/', include('core.checklist_urls'), name='checklist'), url(r'^settings/?$', core.views.settings_views.settings_view, name='settings'), - url(r'^settings_get_checklist_items/?$', GetChecklistItemsView.as_view(), - name='settings_get_checklist_items'), - url(r'^settings_get_checklist_items_for_today/?$', GetChecklistItemsForTodayView.as_view(), - name='settings_get_checklist_items_for_today'), - url(r'^settings_add_checklist_item/?$', CreateChecklistItemView.as_view(), - name='settings_add_checklist_item'), - url(r'^settings_update_checklist_item/?$', UpdateChecklistItemView.as_view(), - name='settings_update_checklist_item'), - url(r'^settings_delete_checklist_item/?$', DeleteChecklistItemView.as_view(), - name='settings_delete_checklist_item'), - url(r'^settings_update_checklist_priority/?$', UpdateChecklistPriorityView.as_view(), - name='settings_update_checklist_priority'), url(r'^trigger_parsing/?$', core.views.trigger_parsing_views.trigger_parsing, name='trigger_parsing'), From 1fde42836f2b06091921522dfe5df5851574b248 Mon Sep 17 00:00:00 2001 From: "sebastian.schreck" Date: Sun, 11 Dec 2016 20:45:38 +0100 Subject: [PATCH 37/71] #99 splitted out trigger parsing urls. to be renamed? --- core/templates/core/account/home.html | 2 +- core/templates/core/ofm/finances.html | 2 +- core/templates/core/ofm/matches.html | 2 +- core/templates/core/ofm/player_statistics.html | 2 +- .../templates/core/ofm/stadium_statistics.html | 2 +- core/tests/unit/views/test_parser_view.py | 12 ++++++------ .../unit/views/test_registration_views.py | 9 +++++++-- core/trigger_parsing_urls.py | 18 ++++++++++++++++++ core/urls.py | 18 ++---------------- 9 files changed, 38 insertions(+), 29 deletions(-) create mode 100644 core/trigger_parsing_urls.py diff --git a/core/templates/core/account/home.html b/core/templates/core/account/home.html index ac22380..905f815 100644 --- a/core/templates/core/account/home.html +++ b/core/templates/core/account/home.html @@ -10,7 +10,7 @@

Willkommen in deinem persönlichen Bereich.


-
+ {% csrf_token %} Um die neuesten Daten von OFM zu laden klicke hier: diff --git a/core/templates/core/ofm/finances.html b/core/templates/core/ofm/finances.html index 5d56ebd..1d5faa8 100644 --- a/core/templates/core/ofm/finances.html +++ b/core/templates/core/ofm/finances.html @@ -6,7 +6,7 @@

Finanzen - {% csrf_token %} +
{% csrf_token %}

{% if matchdays|length > 1 %} diff --git a/core/templates/core/ofm/matches.html b/core/templates/core/ofm/matches.html index 7f37bf7..3e9df23 100644 --- a/core/templates/core/ofm/matches.html +++ b/core/templates/core/ofm/matches.html @@ -6,7 +6,7 @@

Spielplan -
{% csrf_token %}
+
{% csrf_token %}

diff --git a/core/templates/core/ofm/player_statistics.html b/core/templates/core/ofm/player_statistics.html index a7c537a..7ff2c25 100644 --- a/core/templates/core/ofm/player_statistics.html +++ b/core/templates/core/ofm/player_statistics.html @@ -6,7 +6,7 @@

{{players_count}} Spieler -
{% csrf_token %}
+
{% csrf_token %}

{% if matchdays|length > 1 %} diff --git a/core/templates/core/ofm/stadium_statistics.html b/core/templates/core/ofm/stadium_statistics.html index 394ae96..ed78dd4 100644 --- a/core/templates/core/ofm/stadium_statistics.html +++ b/core/templates/core/ofm/stadium_statistics.html @@ -6,7 +6,7 @@

Stadionstatistik -
{% csrf_token %}
+
{% csrf_token %}

diff --git a/core/tests/unit/views/test_parser_view.py b/core/tests/unit/views/test_parser_view.py index f39cfe3..6354fe2 100644 --- a/core/tests/unit/views/test_parser_view.py +++ b/core/tests/unit/views/test_parser_view.py @@ -21,7 +21,7 @@ def setUp(self): @patch('core.views.trigger_parsing_views.SiteManager') @patch('core.managers.parser_manager.MatchdayParser') def test_matchday_parser_view(self, site_manager_mock, matchday_parser_mock): - response = self.client.get(reverse('core:trigger_matchday_parsing')) + response = self.client.get(reverse('core:trigger:trigger_matchday_parsing')) self.assertEqual(response.status_code, 302) assert core.views.trigger_parsing_views.SiteManager.called @@ -31,7 +31,7 @@ def test_matchday_parser_view(self, site_manager_mock, matchday_parser_mock): @patch('core.managers.parser_manager.MatchdayParser') @patch('core.managers.parser_manager.PlayersParser') def test_player_parser_view(self, matchday_parser_mock, site_manager_mock, players_parser_mock): - response = self.client.get(reverse('core:trigger_players_parsing')) + response = self.client.get(reverse('core:trigger:trigger_players_parsing')) self.assertEqual(response.status_code, 302) assert core.views.trigger_parsing_views.SiteManager.called @@ -44,7 +44,7 @@ def test_player_parser_view(self, matchday_parser_mock, site_manager_mock, playe @patch('core.managers.parser_manager.PlayerStatisticsParser') def test_player_statistics_parser_view(self, matchday_parser_mock, player_parser_mock, site_manager_mock, player_statistics_parser_mock): - response = self.client.get(reverse('core:trigger_player_statistics_parsing')) + response = self.client.get(reverse('core:trigger:trigger_player_statistics_parsing')) self.assertEqual(response.status_code, 302) assert core.views.trigger_parsing_views.SiteManager.called @@ -56,7 +56,7 @@ def test_player_statistics_parser_view(self, matchday_parser_mock, player_parser @patch('core.managers.parser_manager.MatchdayParser') @patch('core.managers.parser_manager.FinancesParser') def test_finances_parser_view(self, matchday_parser_mock, site_manager_mock, finances_parser_mock): - response = self.client.get(reverse('core:trigger_finances_parsing')) + response = self.client.get(reverse('core:trigger:trigger_finances_parsing')) self.assertEqual(response.status_code, 302) assert core.views.trigger_parsing_views.SiteManager.called @@ -72,7 +72,7 @@ def test_match_parser_view(self, matchday_parser_mock, match_parser_mock, parse_ site_manager_instance_mock = site_manager_mock.return_value site_manager_instance_mock.browser.page_source = match_schedule_html - response = self.client.get(reverse('core:trigger_match_parsing')) + response = self.client.get(reverse('core:trigger:trigger_match_parsing')) self.assertEqual(response.status_code, 302) assert core.managers.parser_manager.MatchdayParser.return_value.parse.called @@ -89,7 +89,7 @@ def test_match_parser_view(self, matchday_parser_mock, match_parser_mock, parse_ @patch('core.managers.parser_manager.ParserManager.parse_ofm_version') def test_parser_view(self, site_manager_mock, parse_matchday_mock, parse_players_mock, parse_player_statistics_mock, parse_finances_mock, parse_all_matches_mock, parse_awp_mock, parse_version_mock): # noqa - response = self.client.get(reverse('core:trigger_parsing')) + response = self.client.get(reverse('core:trigger:trigger_parsing')) self.assertEqual(response.status_code, 302) assert site_manager_mock.called diff --git a/core/tests/unit/views/test_registration_views.py b/core/tests/unit/views/test_registration_views.py index 8959568..a838c69 100644 --- a/core/tests/unit/views/test_registration_views.py +++ b/core/tests/unit/views/test_registration_views.py @@ -6,8 +6,13 @@ class RegistrationTestCase(TestCase): def setUp(self): - OFMUser.objects.create_user('temporary', 'temporary@ofmhelper.com', 'temporary', ofm_username='ofm', - ofm_password='ofm') + OFMUser.objects.create_user( + username='temporary', + email='temporary@ofmhelper.com', + password='temporary', + ofm_username='ofm', + ofm_password='ofm' + ) def test_register_new_account(self): response = self.client.post(reverse('core:register'), diff --git a/core/trigger_parsing_urls.py b/core/trigger_parsing_urls.py new file mode 100644 index 0000000..effc397 --- /dev/null +++ b/core/trigger_parsing_urls.py @@ -0,0 +1,18 @@ +from django.conf.urls import url +import core.views.trigger_parsing_views + +app_name = 'trigger' +urlpatterns = [ + url(r'^trigger_parsing/?$', core.views.trigger_parsing_views.trigger_parsing, + name='trigger_parsing'), + url(r'^trigger_matchday_parsing/?$', core.views.trigger_parsing_views.trigger_matchday_parsing, + name='trigger_matchday_parsing'), + url(r'^trigger_players_parsing/?$', core.views.trigger_parsing_views.trigger_players_parsing, + name='trigger_players_parsing'), + url(r'^trigger_player_statistics_parsing/?$', core.views.trigger_parsing_views.trigger_player_statistics_parsing, + name='trigger_player_statistics_parsing'), + url(r'^trigger_finances_parsing/?$', core.views.trigger_parsing_views.trigger_finances_parsing, + name='trigger_finances_parsing'), + url(r'^trigger_match_parsing/?$', core.views.trigger_parsing_views.trigger_match_parsing, + name='trigger_match_parsing'), +] diff --git a/core/urls.py b/core/urls.py index 70e392c..39281fb 100644 --- a/core/urls.py +++ b/core/urls.py @@ -14,23 +14,9 @@ url(r'^login/?$', core.views.account_views.login_view, name='login'), url(r'^account/?$', core.views.account_views.account_view, name='account'), url(r'^logout/?$', core.views.account_views.logout_view, name='logout'), + url(r'^settings/?$', core.views.settings_views.settings_view, name='settings'), url(r'^ofm/', include('core.ofm_urls'), name='ofm'), url(r'^checklist/', include('core.checklist_urls'), name='checklist'), - - url(r'^settings/?$', core.views.settings_views.settings_view, - name='settings'), - - url(r'^trigger_parsing/?$', core.views.trigger_parsing_views.trigger_parsing, - name='trigger_parsing'), - url(r'^trigger_matchday_parsing/?$', core.views.trigger_parsing_views.trigger_matchday_parsing, - name='trigger_matchday_parsing'), - url(r'^trigger_players_parsing/?$', core.views.trigger_parsing_views.trigger_players_parsing, - name='trigger_players_parsing'), - url(r'^trigger_player_statistics_parsing/?$', core.views.trigger_parsing_views.trigger_player_statistics_parsing, - name='trigger_player_statistics_parsing'), - url(r'^trigger_finances_parsing/?$', core.views.trigger_parsing_views.trigger_finances_parsing, - name='trigger_finances_parsing'), - url(r'^trigger_match_parsing/?$', core.views.trigger_parsing_views.trigger_match_parsing, - name='trigger_match_parsing'), + url(r'^trigger/', include('core.trigger_parsing_urls'), name='trigger'), ] From 7e159c04cb8e5ca0c92d1a19c6c4eddf708911df Mon Sep 17 00:00:00 2001 From: "sebastian.schreck" Date: Sun, 11 Dec 2016 21:07:48 +0100 Subject: [PATCH 38/71] #99 splitted out account urls --- core/account_urls.py | 14 ++++++++ core/templates/core/account/login.html | 6 ++-- core/templates/core/account/register.html | 6 ++-- core/templates/core/account/settings.html | 4 +-- core/templates/core/includes/navbar.html | 12 +++---- core/tests/unit/test_home_page.py | 6 ++-- core/tests/unit/views/test_login_views.py | 28 +++++++-------- .../unit/views/test_registration_views.py | 26 +++++++------- core/tests/unit/views/test_settings_view.py | 34 ++++++++++--------- core/urls.py | 11 +----- core/views/account_views.py | 18 +++++----- core/views/settings_views.py | 4 +-- core/views/trigger_parsing_views.py | 6 ++-- 13 files changed, 91 insertions(+), 84 deletions(-) create mode 100644 core/account_urls.py diff --git a/core/account_urls.py b/core/account_urls.py new file mode 100644 index 0000000..483b1c9 --- /dev/null +++ b/core/account_urls.py @@ -0,0 +1,14 @@ +from django.conf.urls import url + +import core.views.account_views +import core.views.settings_views +import core.views.trigger_parsing_views + +app_name = 'account' +urlpatterns = [ + url(r'^register/?$', core.views.account_views.register_view, name='register'), + url(r'^login/?$', core.views.account_views.login_view, name='login'), + url(r'^$', core.views.account_views.account_view, name='home'), + url(r'^logout/?$', core.views.account_views.logout_view, name='logout'), + url(r'^settings/?$', core.views.settings_views.settings_view, name='settings'), +] diff --git a/core/templates/core/account/login.html b/core/templates/core/account/login.html index d0aa660..1f3539e 100644 --- a/core/templates/core/account/login.html +++ b/core/templates/core/account/login.html @@ -3,7 +3,7 @@ {% block content %}

Login

-
+ {% csrf_token %}
@@ -17,6 +17,6 @@

Login



- Du hast noch keinen Account? Hier kannst du dich registrieren. + Du hast noch keinen Account? Hier kannst du dich registrieren.

-{% endblock %} \ No newline at end of file +{% endblock %} diff --git a/core/templates/core/account/register.html b/core/templates/core/account/register.html index fdee5fd..1416e7c 100644 --- a/core/templates/core/account/register.html +++ b/core/templates/core/account/register.html @@ -6,9 +6,9 @@

Registrierung

{% if registered %} - Vielen Dank für die Registrierung! Hier geht's zum Login. + Vielen Dank für die Registrierung! Hier geht's zum Login. {% else %} -
+ {% csrf_token %} @@ -63,7 +63,7 @@

Registrierung



- Du hast bereits einen Account bei uns? Hier geht's zum Login. + Du hast bereits einen Account bei uns? Hier geht's zum Login.

{% endif %} {% endblock %} diff --git a/core/templates/core/account/settings.html b/core/templates/core/account/settings.html index 105b142..d622cc4 100644 --- a/core/templates/core/account/settings.html +++ b/core/templates/core/account/settings.html @@ -21,7 +21,7 @@

-
+ {% csrf_token %} @@ -62,7 +62,7 @@

- + {% csrf_token %} diff --git a/core/templates/core/includes/navbar.html b/core/templates/core/includes/navbar.html index 602f7fc..19269e0 100644 --- a/core/templates/core/includes/navbar.html +++ b/core/templates/core/includes/navbar.html @@ -6,24 +6,24 @@