From 28e3aca9c30c1755f1b97ad910879966328f20c0 Mon Sep 17 00:00:00 2001 From: Stefan Date: Tue, 1 Mar 2016 16:43:41 +0100 Subject: [PATCH 1/5] pep8 for schedules app, minor code changes for cleaner code this commit does not introduce any logical changes --- .gitignore | 9 + radio/apps/schedules/admin.py | 75 ++----- .../apps/schedules/migrations/0001_initial.py | 61 +++++- radio/apps/schedules/models.py | 206 ++++++++++++------ radio/apps/schedules/tests.py | 167 +++++++++----- radio/apps/schedules/urls.py | 17 +- radio/apps/schedules/views.py | 47 ++-- 7 files changed, 369 insertions(+), 213 deletions(-) diff --git a/.gitignore b/.gitignore index 5f9d313..6e7d2e4 100755 --- a/.gitignore +++ b/.gitignore @@ -1,3 +1,6 @@ +#django collectstatic files +radio/media/_versions/ + # Byte-compiled / optimized / DLL files __pycache__/ .DS_Store @@ -23,6 +26,12 @@ build/ /django_radio.egg-info/ sitepackages/ +#virtualenv +bin/ +include/ +lib/ +local/ + # Installer logs pip-log.txt pip-delete-this-directory.txt diff --git a/radio/apps/schedules/admin.py b/radio/apps/schedules/admin.py index 982d7c0..a822657 100755 --- a/radio/apps/schedules/admin.py +++ b/radio/apps/schedules/admin.py @@ -27,15 +27,12 @@ from apps.schedules.models import Schedule, ScheduleBoard +try: + from django.utils.encoding import force_unicode +except ImportError: + from django.utils.encoding import force_text as force_unicode -''' -class ScheduleInline(admin.StackedInline): - model = Schedule - extra = 0 - def get_queryset(self, request): - return super(ScheduleInline, self).get_queryset(request).select_related('programme') -''' class ScheduleBoardAdmin(admin.ModelAdmin): list_display = ('name', 'start_date', 'end_date') list_filter = ['start_date', 'end_date'] @@ -56,14 +53,14 @@ def copy_ScheduleBoard(self, request, queryset): try: if ScheduleBoard.objects.get(name=copy_name): pass - # Don't work - # self.message_user(request, _('There is already a calendar with this name \"%s\"') % copy_name, level=messages.ERROR) except ScheduleBoard.DoesNotExist: obj_copy.save() # Live Schedules lives must be created first schedules = [] - schedules.extend(Schedule.objects.filter(schedule_board=obj, type='L')) - schedules.extend(Schedule.objects.filter(schedule_board=obj).exclude(type='L')) + schedules.extend(Schedule.objects.filter( + schedule_board=obj, type='L')) + schedules.extend(Schedule.objects.filter( + schedule_board=obj).exclude(type='L')) for schedule in schedules: schedule_copy = copy.copy(schedule) schedule_copy.id = None @@ -71,47 +68,21 @@ def copy_ScheduleBoard(self, request, queryset): schedule_copy.schedule_board = obj_copy if schedule_copy.source: source = schedule_copy.source - source_copy = Schedule.objects.get(schedule_board=obj_copy, day=source.day, start_hour=source.start_hour, type=source.type, programme=source.programme) + source_copy = Schedule.objects.get( + schedule_board=obj_copy, + day=source.day, + start_hour=source.start_hour, + type=source.type, + programme=source.programme) schedule_copy.source = source_copy schedule_copy.save() copy_ScheduleBoard.short_description = _("Make a Copy of calendar") - - -admin.site.register(ScheduleBoard, ScheduleBoardAdmin) - - -try: - from django.utils.encoding import force_unicode -except ImportError: - from django.utils.encoding import force_text as force_unicode - - - - class FullcalendarAdmin(admin.ModelAdmin): - # change_form_template = 'schedules/fullcalendar.html' - def schedule_detail(self, request): return HttpResponseRedirect(reverse("dashboard:schedule_editor")) - # return redirect('dashboard:schedule_editor') - ''' - model = self.model - opts = model._meta - - app_label = opts.app_label - # create tempate page and extend admin/base.html - config_detail_view_template = 'schedules/fullcalendar.html' - context = { 'data' : Schedule.objects.get(id=2), - 'event_url':'all_events/', 'scheduleBoards' : ScheduleBoard.objects.all().order_by('start_date'), - 'scroll_time': CalendarConfiguration.objects.get().scroll_time.strftime('%H:%M:%S'), - 'first_day': CalendarConfiguration.objects.get().first_day + 1, - 'language' : request.LANGUAGE_CODE, - 'current_scheduleBoard':ScheduleBoard.get_current(datetime.datetime.now())} - return render_to_response(config_detail_view_template , context, context_instance=RequestContext(request)) - ''' def has_add_permission(self, request): return False @@ -125,19 +96,18 @@ def get_urls(self): 'app_name': self.model._meta.app_label, 'model_name': self.model._meta.model_name, } - custom_urls = patterns('', - url(r'^$', - self.admin_site.admin_view(self.schedule_detail), - {}, - # self.admin_site.admin_view(self.change_view), - # {'object_id': '2'}, - name='%s_change' % url_name_prefix), - ) + custom_urls = patterns('', url( + r'^$', + self.admin_site.admin_view(self.schedule_detail), + {}, + name='%s_change' % url_name_prefix)) + # By inserting the custom URLs first, we overwrite the standard URLs. return custom_urls + urls def response_change(self, request, obj): - msg = _('%(obj)s was changed successfully.') % {'obj': force_unicode(obj)} + msg = _( + '%(obj)s was changed successfully.') % {'obj': force_unicode(obj)} if '_continue' in request.POST: return HttpResponseRedirect(request.path) else: @@ -151,4 +121,5 @@ def change_view(self, request, object_id, extra_context=None): ) ''' +admin.site.register(ScheduleBoard, ScheduleBoardAdmin) admin.site.register(Schedule, FullcalendarAdmin) diff --git a/radio/apps/schedules/migrations/0001_initial.py b/radio/apps/schedules/migrations/0001_initial.py index a021b8e..021d67d 100755 --- a/radio/apps/schedules/migrations/0001_initial.py +++ b/radio/apps/schedules/migrations/0001_initial.py @@ -15,11 +15,31 @@ class Migration(migrations.Migration): migrations.CreateModel( name='Schedule', fields=[ - ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), - ('day', models.IntegerField(choices=[(0, 'Monday'), (1, 'Tuesday'), (2, 'Wednesday'), (3, 'Thursday'), (4, 'Friday'), (5, 'Saturday'), (6, 'Sunday')])), + ('id', models.AutoField( + verbose_name='ID', + serialize=False, + auto_created=True, + primary_key=True)), + ('day', models.IntegerField( + choices=[ + (0, 'Monday'), + (1, 'Tuesday'), + (2, 'Wednesday'), + (3, 'Thursday'), + (4, 'Friday'), + (5, 'Saturday'), + (6, 'Sunday')])), ('start_hour', models.TimeField(verbose_name='start time')), - ('type', models.CharField(max_length=1, verbose_name='type', choices=[(b'L', 'live'), (b'B', 'broadcast'), (b'S', 'broadcast syndication')])), - ('programme', models.ForeignKey(verbose_name='programme', to='programmes.Programme')), + ('type', models.CharField( + max_length=1, + verbose_name='type', + choices=[ + (b'L', 'live'), + (b'B', 'broadcast'), + (b'S', 'broadcast syndication')])), + ('programme', models.ForeignKey( + verbose_name='programme', + to='programmes.Programme')), ], options={ 'verbose_name': 'schedule', @@ -30,10 +50,23 @@ class Migration(migrations.Migration): migrations.CreateModel( name='ScheduleBoard', fields=[ - ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), - ('name', models.CharField(unique=True, max_length=255, verbose_name='name')), - ('start_date', models.DateField(null=True, verbose_name='start date', blank=True)), - ('end_date', models.DateField(null=True, verbose_name='end date', blank=True)), + ('id', models.AutoField( + verbose_name='ID', + serialize=False, + auto_created=True, + primary_key=True)), + ('name', models.CharField( + unique=True, + max_length=255, + verbose_name='name')), + ('start_date', models.DateField( + blank=True, + null=True, + verbose_name='start date')), + ('end_date', models.DateField( + blank=True, + null=True, + verbose_name='end date')), ], options={ 'verbose_name': 'schedule board', @@ -44,13 +77,21 @@ class Migration(migrations.Migration): migrations.AddField( model_name='schedule', name='schedule_board', - field=models.ForeignKey(verbose_name='schedule board', to='schedules.ScheduleBoard'), + field=models.ForeignKey( + verbose_name='schedule board', + to='schedules.ScheduleBoard'), preserve_default=True, ), migrations.AddField( model_name='schedule', name='source', - field=models.ForeignKey(on_delete=django.db.models.deletion.SET_NULL, blank=True, to='schedules.Schedule', help_text='It is used when is a broadcast.', null=True, verbose_name='source'), + field=models.ForeignKey( + on_delete=django.db.models.deletion.SET_NULL, + blank=True, + null=True, + to='schedules.Schedule', + help_text='It is used when is a broadcast.', + verbose_name='source'), preserve_default=True, ), ] diff --git a/radio/apps/schedules/models.py b/radio/apps/schedules/models.py index 8cc5d06..96b2eb1 100755 --- a/radio/apps/schedules/models.py +++ b/radio/apps/schedules/models.py @@ -28,7 +28,8 @@ from apps.programmes.models import Programme, Episode -emission_type = (("L", _("live")), +emission_type = ( + ("L", _("live")), ("B", _("broadcast")), ("S", _("broadcast syndication"))) @@ -51,46 +52,59 @@ class ScheduleBoard(models.Model): - name = models.CharField(max_length=255, unique=True, verbose_name=_("name")) - start_date = models.DateField(blank=True, null=True, verbose_name=_('start date')) - end_date = models.DateField(blank=True, null=True, verbose_name=_('end date')) - + name = models.CharField( + max_length=255, unique=True, verbose_name=_("name")) + start_date = models.DateField( + blank=True, null=True, verbose_name=_('start date')) + end_date = models.DateField( + blank=True, null=True, verbose_name=_('end date')) def clean(self): if self.start_date: if self.end_date: if self.start_date > self.end_date: - raise ValidationError(_('end date must be greater than or equal to start date.')) + raise ValidationError(_( + 'end date must be greater than ' + 'or equal to start date.')) # check date collision - qs = ScheduleBoard.objects.filter(start_date__lte=self.end_date, end_date__isnull=True) | ScheduleBoard.objects.filter(start_date__lte=self.end_date, end_date__gte=self.start_date) + qs = ScheduleBoard.objects.filter( + start_date__lte=self.end_date, + end_date__isnull=True + ) | ScheduleBoard.objects.filter( + start_date__lte=self.end_date, + end_date__gte=self.start_date) + if self.pk is not None: qs = qs.exclude(pk=self.pk) if qs.exists(): - raise ValidationError(_('there is another object between this dates.')) + raise ValidationError( + _('there is another object between this dates.')) else: # start_date != None and end_date == None only one can exist - qs = ScheduleBoard.objects.filter(start_date__isnull=False, end_date__isnull=True) | ScheduleBoard.objects.filter(end_date__gte=self.start_date) + qs = ScheduleBoard.objects.filter( + start_date__isnull=False, + end_date__isnull=True + ) | ScheduleBoard.objects.filter(end_date__gte=self.start_date) if self.pk is not None: qs = qs.exclude(pk=self.pk) if qs.exists(): - raise ValidationError(_('there is another object without end_date')) - pass - + raise ValidationError( + _('there is another object without end_date')) elif self.end_date: - raise ValidationError(_('start date cannot be null if end date exists')) - else: - # both None = disable - pass + raise ValidationError( + _('start date cannot be null if end date exists')) def save(self, *args, **kwargs): # rearrange episodes if self.pk is not None: orig = ScheduleBoard.objects.get(pk=self.pk) - if orig.start_date != self.start_date or orig.end_date != self.end_date: # Field has changed + if (orig.start_date != self.start_date or + orig.end_date != self.end_date): # Field has changed super(ScheduleBoard, self).save(*args, **kwargs) - Episode.rearrange_episodes(programme=None, after=datetime.datetime.now()) + Episode.rearrange_episodes( + programme=None, after=datetime.datetime.now()) else: super(ScheduleBoard, self).save(*args, **kwargs) else: @@ -98,7 +112,12 @@ def save(self, *args, **kwargs): @classmethod def get_current(cls, dt): - schedule_board = cls.objects.filter(start_date__lte=dt, end_date__isnull=True).order_by('-start_date') | cls.objects.filter(start_date__lte=dt, end_date__gte=dt).order_by('-start_date') + schedule_board = (cls.objects.filter( + start_date__lte=dt, + end_date__isnull=True).order_by('-start_date') | + cls.objects.filter( + start_date__lte=dt, + end_date__gte=dt).order_by('-start_date')) return schedule_board.first() class Meta: @@ -113,36 +132,63 @@ def __unicode__(self): def delete_ScheduleBoard_handler(sender, **kwargs): Episode.rearrange_episodes(programme=None, after=datetime.datetime.now()) + class Schedule(models.Model): programme = models.ForeignKey(Programme, verbose_name=_("programme")) day = models.IntegerField(choices=WEEKDAY_CHOICES) start_hour = models.TimeField(verbose_name=_('start time')) - type = models.CharField(verbose_name=_("type"), choices=emission_type, max_length=1) - schedule_board = models.ForeignKey(ScheduleBoard, verbose_name=_("schedule board")) - source = models.ForeignKey('self', blank=True, null=True, on_delete=models.SET_NULL, verbose_name=_("source"), help_text=_("It is used when is a broadcast.")) + type = models.CharField( + verbose_name=_("type"), + choices=emission_type, + max_length=1) + schedule_board = models.ForeignKey( + ScheduleBoard, + verbose_name=_("schedule board")) + source = models.ForeignKey( + 'self', + blank=True, + null=True, + on_delete=models.SET_NULL, + verbose_name=_("source"), + help_text=_("It is used when is a broadcast.")) def runtime(self): return self.programme.runtime def __get_rrule(self): start_date = self.programme.start_date - if self.schedule_board.start_date and start_date < self.schedule_board.start_date: + if (self.schedule_board.start_date and + start_date < self.schedule_board.start_date): start_date = self.schedule_board.start_date if self.programme.end_date: end_date = self.programme.end_date - if self.schedule_board.end_date and end_date > self.schedule_board.end_date: + if (self.schedule_board.end_date and + end_date > self.schedule_board.end_date): end_date = self.schedule_board.end_date # Due to rrule we need to add 1 day end_date = end_date + datetime.timedelta(days=1) - return rrule.rrule(rrule.WEEKLY, byweekday=[self.day], dtstart=datetime.datetime.combine(start_date, self.start_hour), until=end_date) + return rrule.rrule( + rrule.WEEKLY, + byweekday=[self.day], + dtstart=datetime.datetime.combine(start_date, self.start_hour), + until=end_date) else: end_date = self.schedule_board.end_date if end_date: # Due to rrule we need to add 1 day end_date = end_date + datetime.timedelta(days=1) - return rrule.rrule(rrule.WEEKLY, byweekday=[self.day], dtstart=datetime.datetime.combine(start_date, self.start_hour), until=end_date) + return rrule.rrule( + rrule.WEEKLY, + byweekday=[self.day], + dtstart=datetime.datetime.combine( + start_date, self.start_hour), + until=end_date) else: - return rrule.rrule(rrule.WEEKLY, byweekday=[self.day], dtstart=datetime.datetime.combine(start_date, self.start_hour)) + return rrule.rrule( + rrule.WEEKLY, + byweekday=[self.day], + dtstart=datetime.datetime.combine( + start_date, self.start_hour)) def dates_between(self, after, before): ''' @@ -165,23 +211,19 @@ def date_after(self, dt): def clean(self): now = datetime.datetime.now() if self.schedule_board.start_date: - dt = datetime.datetime.combine(self.schedule_board.start_date, datetime.time(0, 0)) + dt = datetime.datetime.combine( + self.schedule_board.start_date, datetime.time(0, 0)) if now > dt: dt = now # get the next emission date first_date_start = self.date_after(dt) if first_date_start: first_date_end = first_date_start + self.runtime() - """ - last_date = None - if self.programme.end_date(): - last_date = self.date_before(self.programme.end_date()) - - programme_list = Programme.actives(first_date, last_date); - for programme in programme_list: - pass - """ - schedules, dates_list_list = Schedule.between(after=first_date_start, before=first_date_end, exclude=self, schedule_board=self.schedule_board) + schedules, dates_list_list = Schedule.between( + after=first_date_start, + before=first_date_end, + exclude=self, + schedule_board=self.schedule_board) index = 0 if schedules: for date_list in dates_list_list: @@ -190,31 +232,49 @@ def clean(self): schedule = schedules[index] start_date = date end_date = start_date + schedule.runtime() - raise ValidationError(_('This settings collides with: %(name)s [%(start_date)s %(start_day)s/%(start_month)s/%(start_year)s - %(end_date)s %(end_day)s/%(end_month)s/%(end_year)s ]') - % {'name': schedule.programme.name, 'start_date': start_date.strftime("%H:%M"), 'start_day': start_date.strftime("%d"), - 'start_month': start_date.strftime("%m"), 'start_year': start_date.strftime("%Y"), - 'end_date': end_date.strftime("%H:%M"), 'end_day': end_date.strftime("%d"), 'end_month': end_date.strftime("%m"), 'end_year': end_date.strftime("%Y"), }) - index = index + 1 - - def save(self, *args, **kwargs): - # convert dates due MySQL - # if timezone.is_aware(self.start_hour): - # self.start_hour = timezone.get_current_timezone().normalize(self.start_hour) - super(Schedule, self).save(*args, **kwargs) + raise ValidationError(_( + 'This settings collides with: {name} ' + '[{start_date} - {end_date}]').format( + name=schedule.programme.name, + start_date=start_date.strftime( + "%H:%M %d/%m/%Y"), + end_date=end_date.strftime( + "%H:%M %d/%m/%Y"))) + index = index + 1 @classmethod - def between(cls, after, before, exclude=None, live=False, schedule_board=None): - list_schedules = cls.objects.filter(programme__start_date__lte=before, programme__end_date__isnull=True) | cls.objects.filter(programme__start_date__lte=before, programme__end_date__gte=after) + def between( + cls, after, before, exclude=None, live=False, schedule_board=None): + list_schedules = ( + cls.objects.filter( + programme__start_date__lte=before, + programme__end_date__isnull=True) | + cls.objects.filter( + programme__start_date__lte=before, + programme__end_date__gte=after)) if live: list_schedules = list_schedules.filter(type='L') if schedule_board: - list_schedules = list_schedules.filter(schedule_board=schedule_board) + list_schedules = list_schedules.filter( + schedule_board=schedule_board) else: - list_schedules = list_schedules.filter(schedule_board__start_date__lte=before, schedule_board__end_date__isnull=True) | list_schedules.filter(schedule_board__start_date__lte=before, schedule_board__end_date__gte=after) + list_schedules = ( + list_schedules.filter( + schedule_board__start_date__lte=before, + schedule_board__end_date__isnull=True) | + list_schedules.filter( + schedule_board__start_date__lte=before, + schedule_board__end_date__gte=after)) if exclude: list_schedules = list_schedules.exclude(id=exclude.id) - list_schedules = list_schedules.order_by('-programme__start_date').select_related('programme', 'schedule_board', 'source__programme', 'source__schedule_board') + + list_schedules = list_schedules.order_by( + '-programme__start_date').select_related( + 'programme', + 'schedule_board', + 'source__programme', + 'source__schedule_board') dates = [] schedules = [] @@ -227,45 +287,59 @@ def between(cls, after, before, exclude=None, live=False, schedule_board=None): @classmethod def schedule(cls, dt, exclude=None): - list_schedules = cls.objects.filter(programme__start_date__lte=dt, programme__end_date__isnull=True) | cls.objects.filter(programme__start_date__lte=dt, programme__end_date__gte=dt) + list_schedules = ( + cls.objects.filter( + programme__start_date__lte=dt, + programme__end_date__isnull=True) | + cls.objects.filter( + programme__start_date__lte=dt, + programme__end_date__gte=dt)) if exclude: list_schedules = list_schedules.exclude(id=exclude.id) - list_schedules = list_schedules.select_related('programme', 'schedule_board') + list_schedules = list_schedules.select_related( + 'programme', 'schedule_board') earlier_date = None earlier_schedule = None for schedule in list_schedules: - # if schedule != exclude: date = schedule.date_before(dt) if date and (earlier_date is None or date > earlier_date): earlier_date = date earlier_schedule = schedule - if earlier_schedule is None or dt > earlier_date + earlier_schedule.runtime(): # Todo: check + if (earlier_schedule is None or + dt > earlier_date + earlier_schedule.runtime()): + # XXX Todo: check return None, None return earlier_schedule, earlier_date @classmethod def get_next_date(cls, programme, after): list_schedules = cls.objects.filter(programme=programme, type='L') - list_schedules = list_schedules.filter(programme__end_date__isnull=True) | list_schedules.filter(programme__end_date__gte=after) - list_schedules = list_schedules.filter(schedule_board__start_date__isnull=False, schedule_board__end_date__isnull=True) | list_schedules.filter(schedule_board__end_date__gte=after) - # list_schedules = list_schedules.select_related('programme', 'schedule_board', 'source__programme', 'source__schedule_board') + list_schedules = ( + list_schedules.filter(programme__end_date__isnull=True) | + list_schedules.filter(programme__end_date__gte=after)) + list_schedules = ( + list_schedules.filter( + schedule_board__start_date__isnull=False, + schedule_board__end_date__isnull=True) | + list_schedules.filter(schedule_board__end_date__gte=after)) + closer_date = None closer_schedule = None for schedule in list_schedules: - # if schedule != exclude: date = schedule.date_after(after) if date and (closer_date is None or date < closer_date): closer_date = date closer_schedule = schedule - if closer_schedule is None: # Todo: check + if closer_schedule is None: # XXX Todo: check return None, None return closer_schedule, closer_date def __unicode__(self): - return self.get_day_display() + ' - ' + self.start_hour.strftime('%H:%M') + return ' '.join( + self.get_day_display(), + '-', + self.start_hour.strftime('%H:%M')) class Meta: verbose_name = _('schedule') verbose_name_plural = _('schedules') - - diff --git a/radio/apps/schedules/tests.py b/radio/apps/schedules/tests.py index 5a55bbc..7168bb7 100755 --- a/radio/apps/schedules/tests.py +++ b/radio/apps/schedules/tests.py @@ -23,62 +23,93 @@ from mock import patch from apps.programmes.models import Programme, Episode -from apps.schedules.models import ScheduleBoard, Schedule, MO, TU, WE, TH, FR, SA, SU +from apps.schedules.models import ScheduleBoard, Schedule +from apps.schedules.models import MO, TU, WE, TH, FR, SA, SU def to_relativedelta(tdelta): return relativedelta(seconds=int(tdelta.total_seconds()), microseconds=tdelta.microseconds) + class ProgrammeMethodTests(TestCase): def setUp(self): - midnight_programme = Programme.objects.create(name="Programme 00:00 - 09:00", synopsis="This is a description", - start_date=datetime.datetime(2014, 1, 1, 0, 0, 0, 0), - end_date=datetime.datetime(2014, 1, 31, 12, 0, 0, 0), - current_season=1, runtime=540) - - schedule_board = ScheduleBoard(name='Board', start_date=datetime.datetime(2014, 1, 1, 0, 0, 0, 0)) + midnight_programme = Programme.objects.create( + name="Programme 00:00 - 09:00", + synopsis="This is a description", + start_date=datetime.datetime(2014, 1, 1, 0, 0, 0, 0), + end_date=datetime.datetime(2014, 1, 31, 12, 0, 0, 0), + current_season=1, runtime=540) + + schedule_board = ScheduleBoard( + name='Board', start_date=datetime.datetime(2014, 1, 1, 0, 0, 0, 0)) schedule_board.save() + start_hour = datetime.time(0, 0, 0) - Schedule.objects.create(programme=midnight_programme, day=MO, start_hour=start_hour, type='L', schedule_board=schedule_board) - Schedule.objects.create(programme=midnight_programme, day=TU, start_hour=start_hour, type='L', schedule_board=schedule_board) - Schedule.objects.create(programme=midnight_programme, day=WE, start_hour=start_hour, type='L', schedule_board=schedule_board) - Schedule.objects.create(programme=midnight_programme, day=TH, start_hour=start_hour, type='L', schedule_board=schedule_board) - Schedule.objects.create(programme=midnight_programme, day=FR, start_hour=start_hour, type='L', schedule_board=schedule_board) - Schedule.objects.create(programme=midnight_programme, day=SA, start_hour=start_hour, type='L', schedule_board=schedule_board) - Schedule.objects.create(programme=midnight_programme, day=SU, start_hour=start_hour, type='L', schedule_board=schedule_board) - - programme = Programme.objects.create(name="Programme 09:00 - 10:00", synopsis="This is a description", - start_date=datetime.datetime(2014, 1, 1), - end_date=datetime.datetime(2014, 1, 31), - current_season=1, runtime=60) - Schedule.objects.create(programme=programme, day=MO, start_hour=datetime.time(9, 0, 0), type='L', schedule_board=schedule_board) - Schedule.objects.create(programme=programme, day=WE, start_hour=datetime.time(9, 0, 0), type='L', schedule_board=schedule_board) - Schedule.objects.create(programme=programme, day=FR, start_hour=datetime.time(9, 0, 0), type='L', schedule_board=schedule_board) - - programme = Programme.objects.create(name="Programme 10:00 - 12:00", synopsis="This is a description", - start_date=datetime.datetime(2014, 1, 1), - end_date=datetime.datetime(2014, 1, 31), - current_season=1, runtime=120) - Schedule.objects.create(programme=programme, day=MO, start_hour=datetime.time(10, 0, 0), type='L', schedule_board=schedule_board) - Schedule.objects.create(programme=programme, day=WE, start_hour=datetime.time(10, 0, 0), type='L', schedule_board=schedule_board) - Schedule.objects.create(programme=programme, day=FR, start_hour=datetime.time(10, 0, 0), type='L', schedule_board=schedule_board) + for day in (MO, TU, WE, TH, FR, SA, SU): + Schedule.objects.create( + programme=midnight_programme, + day=day, + start_hour=start_hour, + type='L', + schedule_board=schedule_board) + + programme = Programme.objects.create( + name="Programme 09:00 - 10:00", + synopsis="This is a description", + start_date=datetime.datetime(2014, 1, 1), + end_date=datetime.datetime(2014, 1, 31), + current_season=1, runtime=60) + + for day in (MO, WE, FR): + Schedule.objects.create( + programme=programme, + day=day, + start_hour=datetime.time(9, 0, 0), + type='L', + schedule_board=schedule_board) + + programme = Programme.objects.create( + name="Programme 10:00 - 12:00", + synopsis="This is a description", + start_date=datetime.datetime(2014, 1, 1), + end_date=datetime.datetime(2014, 1, 31), + current_season=1, runtime=120) + + for day in (MO, WE, FR): + Schedule.objects.create( + programme=programme, + day=day, + start_hour=datetime.time(10, 0, 0), + type='L', + schedule_board=schedule_board) for schedule in Schedule.objects.all(): schedule.clean() def test_runtime(self): programme = Programme.objects.get(name="Programme 00:00 - 09:00") - self.assertEqual(relativedelta(hours=+9), to_relativedelta(programme.runtime)) + self.assertEqual( + relativedelta(hours=+9), to_relativedelta(programme.runtime)) def test_day_schedule(self): - schedules, dates = Schedule.between(datetime.datetime(2014, 1, 6), datetime.datetime(2014, 1, 7)) + schedules, dates = Schedule.between( + datetime.datetime(2014, 1, 6), datetime.datetime(2014, 1, 7)) self.assertEqual(4, len(schedules)) - schedule_1 = Schedule.objects.get(programme=Programme.objects.get(name="Programme 00:00 - 09:00"), day=MO) - schedule_2 = Schedule.objects.get(programme=Programme.objects.get(name="Programme 09:00 - 10:00"), day=MO) - schedule_3 = Schedule.objects.get(programme=Programme.objects.get(name="Programme 10:00 - 12:00"), day=MO) - schedule_4 = Schedule.objects.get(programme=Programme.objects.get(name="Programme 00:00 - 09:00"), day=TU) + + schedule_1 = Schedule.objects.get( + programme=Programme.objects.get(name="Programme 00:00 - 09:00"), + day=MO) + schedule_2 = Schedule.objects.get( + programme=Programme.objects.get(name="Programme 09:00 - 10:00"), + day=MO) + schedule_3 = Schedule.objects.get( + programme=Programme.objects.get(name="Programme 10:00 - 12:00"), + day=MO) + schedule_4 = Schedule.objects.get( + programme=Programme.objects.get(name="Programme 00:00 - 09:00"), + day=TU) self.assertTrue(schedule_1 in schedules) self.assertTrue(schedule_2 in schedules) self.assertTrue(schedule_3 in schedules) @@ -87,25 +118,37 @@ def test_day_schedule(self): def test_now_playing_1(self): now_mock = datetime.datetime(2014, 1, 6, 0, 0, 0, 0) schedule, date = Schedule.schedule(now_mock) - schedule_1 = Schedule.objects.get(programme=Programme.objects.get(name="Programme 00:00 - 09:00"), day=MO) + schedule_1 = Schedule.objects.get( + programme=Programme.objects.get(name="Programme 00:00 - 09:00"), + day=MO) self.assertEqual(schedule_1, schedule) - self.assertEqual(datetime.datetime.combine(now_mock, schedule_1.start_hour), date) + self.assertEqual( + datetime.datetime.combine(now_mock, schedule_1.start_hour), date) def test_now_playing_2(self): now_mock = datetime.datetime(2014, 1, 7, 0, 0, 0, 0) schedule, date = Schedule.schedule(now_mock) - schedule_1 = Schedule.objects.get(programme=Programme.objects.get(name="Programme 00:00 - 09:00"), day=TU) + schedule_1 = Schedule.objects.get( + programme=Programme.objects.get(name="Programme 00:00 - 09:00"), + day=TU) self.assertEqual(schedule_1, schedule) - self.assertEqual(datetime.datetime.combine(now_mock, schedule_1.start_hour), date) - - + self.assertEqual( + datetime.datetime.combine(now_mock, schedule_1.start_hour), date) class ScheduleBoardMethodTests(TestCase): def setUp(self): - ScheduleBoard.objects.create(name="january", start_date=datetime.datetime(2014, 1, 1), end_date=datetime.datetime(2014, 1, 31)) - ScheduleBoard.objects.create(name="1_14_february", start_date=datetime.datetime(2014, 2, 1), end_date=datetime.datetime(2014, 2, 14)) - ScheduleBoard.objects.create(name="after_14_february", start_date=datetime.datetime(2014, 2, 15)) + ScheduleBoard.objects.create( + name="january", + start_date=datetime.datetime(2014, 1, 1), + end_date=datetime.datetime(2014, 1, 31)) + ScheduleBoard.objects.create( + name="1_14_february", + start_date=datetime.datetime(2014, 2, 1), + end_date=datetime.datetime(2014, 2, 14)) + ScheduleBoard.objects.create( + name="after_14_february", + start_date=datetime.datetime(2014, 2, 15)) for schedule_board in ScheduleBoard.objects.all(): schedule_board.clean() @@ -114,20 +157,32 @@ def test_runtime(self): february_board = ScheduleBoard.objects.get(name="1_14_february") after_board = ScheduleBoard.objects.get(name="after_14_february") - self.assertEqual(None, ScheduleBoard.get_current(datetime.datetime(2013, 12, 1, 0, 0, 0, 0))) - self.assertEqual(january_board, ScheduleBoard.get_current(datetime.datetime(2014, 1, 1, 0, 0, 0, 0))) - self.assertEqual(january_board, ScheduleBoard.get_current(datetime.datetime(2014, 1, 31, 0, 0, 0, 0))) - self.assertEqual(january_board, ScheduleBoard.get_current(datetime.datetime(2014, 1, 31, 12, 0, 0, 0))) - self.assertEqual(february_board, ScheduleBoard.get_current(datetime.datetime(2014, 2, 1, 0, 0, 0, 0))) - self.assertEqual(february_board, ScheduleBoard.get_current(datetime.datetime(2014, 2, 14, 0, 0, 0, 0))) - self.assertEqual(after_board, ScheduleBoard.get_current(datetime.datetime(2014, 2, 15, 0, 0, 0, 0))) - self.assertEqual(after_board, ScheduleBoard.get_current(datetime.datetime(2014, 6, 1, 0, 0, 0, 0))) + self.assertEqual(None, ScheduleBoard.get_current( + datetime.datetime(2013, 12, 1, 0, 0, 0, 0))) + self.assertEqual(january_board, ScheduleBoard.get_current( + datetime.datetime(2014, 1, 1, 0, 0, 0, 0))) + self.assertEqual(january_board, ScheduleBoard.get_current( + datetime.datetime(2014, 1, 31, 0, 0, 0, 0))) + self.assertEqual(january_board, ScheduleBoard.get_current( + datetime.datetime(2014, 1, 31, 12, 0, 0, 0))) + self.assertEqual(february_board, ScheduleBoard.get_current( + datetime.datetime(2014, 2, 1, 0, 0, 0, 0))) + self.assertEqual(february_board, ScheduleBoard.get_current( + datetime.datetime(2014, 2, 14, 0, 0, 0, 0))) + self.assertEqual(after_board, ScheduleBoard.get_current( + datetime.datetime(2014, 2, 15, 0, 0, 0, 0))) + self.assertEqual(after_board, ScheduleBoard.get_current( + datetime.datetime(2014, 6, 1, 0, 0, 0, 0))) def test_validation_exception_1(self): - schedule_board = ScheduleBoard.objects.create(name="2_14_february", start_date=datetime.datetime(2014, 2, 2), end_date=datetime.datetime(2014, 2, 14)) + schedule_board = ScheduleBoard.objects.create( + name="2_14_february", + start_date=datetime.datetime(2014, 2, 2), + end_date=datetime.datetime(2014, 2, 14)) self.assertRaises(ValidationError, schedule_board.clean) def test_validation_exception_2(self): - schedule_board = ScheduleBoard.objects.create(name="after_18_february", start_date=datetime.datetime(2014, 2, 18)) + schedule_board = ScheduleBoard.objects.create( + name="after_18_february", + start_date=datetime.datetime(2014, 2, 18)) self.assertRaises(ValidationError, schedule_board.clean) - diff --git a/radio/apps/schedules/urls.py b/radio/apps/schedules/urls.py index 4c55b69..c180f5b 100755 --- a/radio/apps/schedules/urls.py +++ b/radio/apps/schedules/urls.py @@ -20,17 +20,14 @@ from apps.schedules import views -urlpatterns = patterns('', +urlpatterns = [ url(r'^$', views.schedule_list, name='list'), url(r'^feed_schedules/', views.feed_schedules, name='feed_schedules'), -) +] - -""" -url(r'^$', - ListView.as_view( - queryset=Episode.objects.order_by('-start_date')[:5], - template_name='schedules/schedules_list.html'), - name='list'), -""" +# url(r'^$', +# ListView.as_view( +# queryset=Episode.objects.order_by('-start_date')[:5], +# template_name='schedules/schedules_list.html'), +# name='list'), diff --git a/radio/apps/schedules/views.py b/radio/apps/schedules/views.py index 7315710..7a30c38 100755 --- a/radio/apps/schedules/views.py +++ b/radio/apps/schedules/views.py @@ -40,8 +40,8 @@ def schedule_list(request): 'min_time': calendar_configuration.min_time.strftime('%H:%M:%S'), 'max_time': calendar_configuration.max_time.strftime('%H:%M:%S'), 'first_day': calendar_configuration.first_day + 1, - 'language' : request.LANGUAGE_CODE, - 'feed_schedules' : reverse('schedules:feed_schedules'), + 'language': request.LANGUAGE_CODE, + 'feed_schedules': reverse('schedules:feed_schedules'), } return render(request, 'schedules/schedules_list.html', context) @@ -49,14 +49,15 @@ def schedule_list(request): def feed_schedules(request): start = datetime.datetime.strptime(request.GET.get('start'), '%Y-%m-%d') end = datetime.datetime.strptime(request.GET.get('end'), '%Y-%m-%d') - return HttpResponse(json.dumps(__get_events(after=start, before=end, json_mode=True)), content_type='application/json') + return HttpResponse(json.dumps( + __get_events(after=start, before=end, json_mode=True)), + content_type='application/json') - -background_colours = { "L": "#F9AD81", "B": "#C4DF9B", "S": "#8493CA" } -text_colours = { "L": "black", "B": "black", "S": "black" } - def __get_events(after, before, json_mode=False): + background_colours = {"L": "#F9AD81", "B": "#C4DF9B", "S": "#8493CA"} + text_colours = {"L": "black", "B": "black", "S": "black"} + next_schedules, next_dates = Schedule.between(after=after, before=before) schedules = [] dates = [] @@ -88,24 +89,32 @@ def __get_events(after, before, json_mode=False): episodes.append(episode) if episode: - url = reverse('programmes:episode_detail', args=(schedule.programme.slug, episode.season, episode.number_in_season,)) + url = reverse( + 'programmes:episode_detail', args=( + schedule.programme.slug, + episode.season, + episode.number_in_season,)) else: - url = reverse('programmes:detail', args=(schedule.programme.slug,)) - - - event_entry = {'id':schedule.id, 'start':str(date), 'end':str(date + schedule.runtime()), - 'allDay':False, 'title': schedule.programme.name, 'type':schedule.type, - 'textColor':text_colours[schedule.type], - 'backgroundColor':background_colours[schedule.type], - 'url':url} + url = reverse( + 'programmes:detail', args=(schedule.programme.slug,)) + + event_entry = { + 'id': schedule.id, + 'start': str(date), + 'end': str(date + schedule.runtime()), + 'allDay': False, + 'title': schedule.programme.name, + 'type': schedule.type, + 'textColor': text_colours[schedule.type], + 'backgroundColor': background_colours[schedule.type], + 'url': url} event_list.append(event_entry) if json_mode: return event_list else: if (schedules): - dates, schedules, episodes = (list(t) for t in zip(*sorted(zip(dates, schedules, episodes)))) + dates, schedules, episodes = (list(t) for t in zip( + *sorted(zip(dates, schedules, episodes)))) return zip(schedules, dates, episodes) return None - - From f16c522ee9704b95bb8d05c5e64e1b0795b67e2b Mon Sep 17 00:00:00 2001 From: Stefan Date: Tue, 1 Mar 2016 17:11:27 +0100 Subject: [PATCH 2/5] some more pep8 changes for schedules app --- radio/apps/schedules/admin.py | 4 ++-- radio/apps/schedules/models.py | 33 ++++++++++++++++++--------------- radio/apps/schedules/views.py | 17 ++++++++--------- 3 files changed, 28 insertions(+), 26 deletions(-) diff --git a/radio/apps/schedules/admin.py b/radio/apps/schedules/admin.py index a822657..ff6ca61 100755 --- a/radio/apps/schedules/admin.py +++ b/radio/apps/schedules/admin.py @@ -106,8 +106,8 @@ def get_urls(self): return custom_urls + urls def response_change(self, request, obj): - msg = _( - '%(obj)s was changed successfully.') % {'obj': force_unicode(obj)} + msg = _('{obj} was changed successfully.'.format( + obj=force_unicode(obj))) if '_continue' in request.POST: return HttpResponseRedirect(request.path) else: diff --git a/radio/apps/schedules/models.py b/radio/apps/schedules/models.py index 96b2eb1..2dbc60d 100755 --- a/radio/apps/schedules/models.py +++ b/radio/apps/schedules/models.py @@ -67,12 +67,13 @@ def clean(self): 'end date must be greater than ' 'or equal to start date.')) # check date collision - qs = ScheduleBoard.objects.filter( - start_date__lte=self.end_date, - end_date__isnull=True - ) | ScheduleBoard.objects.filter( - start_date__lte=self.end_date, - end_date__gte=self.start_date) + qs = ( + ScheduleBoard.objects.filter( + start_date__lte=self.end_date, + end_date__isnull=True) | + ScheduleBoard.objects.filter( + start_date__lte=self.end_date, + end_date__gte=self.start_date)) if self.pk is not None: qs = qs.exclude(pk=self.pk) @@ -82,10 +83,12 @@ def clean(self): else: # start_date != None and end_date == None only one can exist - qs = ScheduleBoard.objects.filter( - start_date__isnull=False, - end_date__isnull=True - ) | ScheduleBoard.objects.filter(end_date__gte=self.start_date) + qs = ( + ScheduleBoard.objects.filter( + start_date__isnull=False, + end_date__isnull=True) | + ScheduleBoard.objects.filter( + end_date__gte=self.start_date)) if self.pk is not None: qs = qs.exclude(pk=self.pk) if qs.exists(): @@ -112,9 +115,10 @@ def save(self, *args, **kwargs): @classmethod def get_current(cls, dt): - schedule_board = (cls.objects.filter( - start_date__lte=dt, - end_date__isnull=True).order_by('-start_date') | + schedule_board = ( + cls.objects.filter( + start_date__lte=dt, + end_date__isnull=True).order_by('-start_date') | cls.objects.filter( start_date__lte=dt, end_date__gte=dt).order_by('-start_date')) @@ -335,9 +339,8 @@ def get_next_date(cls, programme, after): return closer_schedule, closer_date def __unicode__(self): - return ' '.join( + return ' - '.join( self.get_day_display(), - '-', self.start_hour.strftime('%H:%M')) class Meta: diff --git a/radio/apps/schedules/views.py b/radio/apps/schedules/views.py index 7a30c38..89c373b 100755 --- a/radio/apps/schedules/views.py +++ b/radio/apps/schedules/views.py @@ -49,8 +49,8 @@ def schedule_list(request): def feed_schedules(request): start = datetime.datetime.strptime(request.GET.get('start'), '%Y-%m-%d') end = datetime.datetime.strptime(request.GET.get('end'), '%Y-%m-%d') - return HttpResponse(json.dumps( - __get_events(after=start, before=end, json_mode=True)), + return HttpResponse( + json.dumps(__get_events(after=start, before=end, json_mode=True)), content_type='application/json') @@ -89,14 +89,13 @@ def __get_events(after, before, json_mode=False): episodes.append(episode) if episode: - url = reverse( - 'programmes:episode_detail', args=( - schedule.programme.slug, - episode.season, - episode.number_in_season,)) + url = reverse('programmes:episode_detail', args=( + schedule.programme.slug, + episode.season, + episode.number_in_season,)) else: - url = reverse( - 'programmes:detail', args=(schedule.programme.slug,)) + url = reverse('programmes:detail', args=( + schedule.programme.slug,)) event_entry = { 'id': schedule.id, From 5baccd5bb9c837170de174a32b0a9c129f62d4e3 Mon Sep 17 00:00:00 2001 From: Stefan Date: Tue, 1 Mar 2016 23:14:49 +0100 Subject: [PATCH 3/5] fix unicode built-in for Schedule model --- radio/apps/schedules/models.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/radio/apps/schedules/models.py b/radio/apps/schedules/models.py index 2dbc60d..3e8a041 100755 --- a/radio/apps/schedules/models.py +++ b/radio/apps/schedules/models.py @@ -339,9 +339,8 @@ def get_next_date(cls, programme, after): return closer_schedule, closer_date def __unicode__(self): - return ' - '.join( - self.get_day_display(), - self.start_hour.strftime('%H:%M')) + return ' - '.join([self.get_day_display(), + self.start_hour.strftime('%H:%M')]) class Meta: verbose_name = _('schedule') From 458dffbcc5ecaf644f3a7249baa9c5c37e02ac6d Mon Sep 17 00:00:00 2001 From: Stefan Date: Mon, 7 Mar 2016 09:19:57 +0100 Subject: [PATCH 4/5] back to 120 char line length --- radio/apps/schedules/admin.py | 9 ++---- radio/apps/schedules/models.py | 32 +++++++------------ radio/apps/schedules/tests.py | 57 ++++++++++------------------------ 3 files changed, 31 insertions(+), 67 deletions(-) diff --git a/radio/apps/schedules/admin.py b/radio/apps/schedules/admin.py index 1b317e4..372195f 100755 --- a/radio/apps/schedules/admin.py +++ b/radio/apps/schedules/admin.py @@ -59,10 +59,8 @@ def copy_ScheduleBoard(self, request, queryset): obj_copy.save() # Live Schedules lives must be created first schedules = [] - schedules.extend(Schedule.objects.filter( - schedule_board=obj, type='L')) - schedules.extend(Schedule.objects.filter( - schedule_board=obj).exclude(type='L')) + schedules.extend(Schedule.objects.filter(schedule_board=obj, type='L')) + schedules.extend(Schedule.objects.filter(schedule_board=obj).exclude(type='L')) for schedule in schedules: schedule_copy = copy.copy(schedule) schedule_copy.id = None @@ -110,8 +108,7 @@ def get_urls(self): return custom_urls + urls def response_change(self, request, obj): - msg = _('{obj} was changed successfully.'.format( - obj=force_unicode(obj))) + msg = _('{obj} was changed successfully.'.format(obj=force_unicode(obj))) if '_continue' in request.POST: return HttpResponseRedirect(request.path) else: diff --git a/radio/apps/schedules/models.py b/radio/apps/schedules/models.py index b65ee1e..36cda85 100755 --- a/radio/apps/schedules/models.py +++ b/radio/apps/schedules/models.py @@ -85,18 +85,15 @@ def clean(self): pass elif self.end_date: - raise ValidationError( - _('start date cannot be null if end date exists')) + raise ValidationError(_('start date cannot be null if end date exists')) def save(self, *args, **kwargs): # rearrange episodes if self.pk is not None: orig = ScheduleBoard.objects.get(pk=self.pk) - if (orig.start_date != self.start_date or - orig.end_date != self.end_date): # Field has changed + if (orig.start_date != self.start_date or orig.end_date != self.end_date): # Field has changed super(ScheduleBoard, self).save(*args, **kwargs) - Episode.rearrange_episodes( - programme=None, after=datetime.datetime.now()) + Episode.rearrange_episodes(programme=None, after=datetime.datetime.now()) else: super(ScheduleBoard, self).save(*args, **kwargs) else: @@ -139,13 +136,11 @@ def runtime(self): def __get_rrule(self): start_date = self.programme.start_date - if (self.schedule_board.start_date and - start_date < self.schedule_board.start_date): + if (self.schedule_board.start_date and start_date < self.schedule_board.start_date): start_date = self.schedule_board.start_date if self.programme.end_date: end_date = self.programme.end_date - if (self.schedule_board.end_date and - end_date > self.schedule_board.end_date): + if (self.schedule_board.end_date and end_date > self.schedule_board.end_date): end_date = self.schedule_board.end_date # Due to rrule we need to add 1 day end_date = end_date + datetime.timedelta(days=1) @@ -190,8 +185,7 @@ def date_after(self, dt): def clean(self): now = datetime.datetime.now() if self.schedule_board.start_date: - dt = datetime.datetime.combine( - self.schedule_board.start_date, datetime.time(0, 0)) + dt = datetime.datetime.combine(self.schedule_board.start_date, datetime.time(0, 0)) if now > dt: dt = now # get the next emission date @@ -217,7 +211,7 @@ def clean(self): ) ) - index = index + 1 + index += 1 def save(self, *args, **kwargs): # convert dates due MySQL @@ -234,8 +228,7 @@ def between(cls, after, before, exclude=None, live=False, schedule_board=None): if live: list_schedules = list_schedules.filter(type='L') if schedule_board: - list_schedules = list_schedules.filter( - schedule_board=schedule_board) + list_schedules = list_schedules.filter(schedule_board=schedule_board) else: list_schedules = ( list_schedules.filter(schedule_board__start_date__lte=before, schedule_board__end_date__isnull=True) | @@ -273,9 +266,7 @@ def schedule(cls, dt, exclude=None): if date and (earlier_date is None or date > earlier_date): earlier_date = date earlier_schedule = schedule - if (earlier_schedule is None or - dt > earlier_date + earlier_schedule.runtime()): - # XXX Todo: check + if (earlier_schedule is None or dt > earlier_date + earlier_schedule.runtime()): # Todo: check return None, None return earlier_schedule, earlier_date @@ -297,13 +288,12 @@ def get_next_date(cls, programme, after): if date and (closer_date is None or date < closer_date): closer_date = date closer_schedule = schedule - if closer_schedule is None: # XXX Todo: check + if closer_schedule is None: # Todo: check return None, None return closer_schedule, closer_date def __unicode__(self): - return ' - '.join([self.get_day_display(), - self.start_hour.strftime('%H:%M')]) + return ' - '.join([self.get_day_display(), self.start_hour.strftime('%H:%M')]) class Meta: verbose_name = _('schedule') diff --git a/radio/apps/schedules/tests.py b/radio/apps/schedules/tests.py index 968848d..84fdca3 100755 --- a/radio/apps/schedules/tests.py +++ b/radio/apps/schedules/tests.py @@ -82,26 +82,16 @@ def setUp(self): def test_runtime(self): programme = Programme.objects.get(name="Programme 00:00 - 09:00") - self.assertEqual( - relativedelta(hours=+9), to_relativedelta(programme.runtime)) + self.assertEqual(relativedelta(hours=+9), to_relativedelta(programme.runtime)) def test_day_schedule(self): - schedules, dates = Schedule.between( - datetime.datetime(2014, 1, 6), datetime.datetime(2014, 1, 7)) + schedules, dates = Schedule.between(datetime.datetime(2014, 1, 6), datetime.datetime(2014, 1, 7)) self.assertEqual(4, len(schedules)) - schedule_1 = Schedule.objects.get( - programme=Programme.objects.get(name="Programme 00:00 - 09:00"), - day=MO) - schedule_2 = Schedule.objects.get( - programme=Programme.objects.get(name="Programme 09:00 - 10:00"), - day=MO) - schedule_3 = Schedule.objects.get( - programme=Programme.objects.get(name="Programme 10:00 - 12:00"), - day=MO) - schedule_4 = Schedule.objects.get( - programme=Programme.objects.get(name="Programme 00:00 - 09:00"), - day=TU) + schedule_1 = Schedule.objects.get(programme=Programme.objects.get(name="Programme 00:00 - 09:00"), day=MO) + schedule_2 = Schedule.objects.get(programme=Programme.objects.get(name="Programme 09:00 - 10:00"), day=MO) + schedule_3 = Schedule.objects.get(programme=Programme.objects.get(name="Programme 10:00 - 12:00"), day=MO) + schedule_4 = Schedule.objects.get(programme=Programme.objects.get(name="Programme 00:00 - 09:00"), day=TU) self.assertTrue(schedule_1 in schedules) self.assertTrue(schedule_2 in schedules) self.assertTrue(schedule_3 in schedules) @@ -110,19 +100,14 @@ def test_day_schedule(self): def test_now_playing_1(self): now_mock = datetime.datetime(2014, 1, 6, 0, 0, 0, 0) schedule, date = Schedule.schedule(now_mock) - schedule_1 = Schedule.objects.get( - programme=Programme.objects.get(name="Programme 00:00 - 09:00"), - day=MO) + schedule_1 = Schedule.objects.get(programme=Programme.objects.get(name="Programme 00:00 - 09:00"), day=MO) self.assertEqual(schedule_1, schedule) - self.assertEqual( - datetime.datetime.combine(now_mock, schedule_1.start_hour), date) + self.assertEqual(datetime.datetime.combine(now_mock, schedule_1.start_hour), date) def test_now_playing_2(self): now_mock = datetime.datetime(2014, 1, 7, 0, 0, 0, 0) schedule, date = Schedule.schedule(now_mock) - schedule_1 = Schedule.objects.get( - programme=Programme.objects.get(name="Programme 00:00 - 09:00"), - day=TU) + schedule_1 = Schedule.objects.get(programme=Programme.objects.get(name="Programme 00:00 - 09:00"), day=TU) self.assertEqual(schedule_1, schedule) self.assertEqual(datetime.datetime.combine(now_mock, schedule_1.start_hour), date) @@ -146,22 +131,14 @@ def test_runtime(self): february_board = ScheduleBoard.objects.get(name="1_14_february") after_board = ScheduleBoard.objects.get(name="after_14_february") - self.assertEqual(None, ScheduleBoard.get_current( - datetime.datetime(2013, 12, 1, 0, 0, 0, 0))) - self.assertEqual(january_board, ScheduleBoard.get_current( - datetime.datetime(2014, 1, 1, 0, 0, 0, 0))) - self.assertEqual(january_board, ScheduleBoard.get_current( - datetime.datetime(2014, 1, 31, 0, 0, 0, 0))) - self.assertEqual(january_board, ScheduleBoard.get_current( - datetime.datetime(2014, 1, 31, 12, 0, 0, 0))) - self.assertEqual(february_board, ScheduleBoard.get_current( - datetime.datetime(2014, 2, 1, 0, 0, 0, 0))) - self.assertEqual(february_board, ScheduleBoard.get_current( - datetime.datetime(2014, 2, 14, 0, 0, 0, 0))) - self.assertEqual(after_board, ScheduleBoard.get_current( - datetime.datetime(2014, 2, 15, 0, 0, 0, 0))) - self.assertEqual(after_board, ScheduleBoard.get_current( - datetime.datetime(2014, 6, 1, 0, 0, 0, 0))) + self.assertEqual(None, ScheduleBoard.get_current(datetime.datetime(2013, 12, 1, 0, 0, 0, 0))) + self.assertEqual(january_board, ScheduleBoard.get_current(datetime.datetime(2014, 1, 1, 0, 0, 0, 0))) + self.assertEqual(january_board, ScheduleBoard.get_current(datetime.datetime(2014, 1, 31, 0, 0, 0, 0))) + self.assertEqual(january_board, ScheduleBoard.get_current(datetime.datetime(2014, 1, 31, 12, 0, 0, 0))) + self.assertEqual(february_board, ScheduleBoard.get_current(datetime.datetime(2014, 2, 1, 0, 0, 0, 0))) + self.assertEqual(february_board, ScheduleBoard.get_current(datetime.datetime(2014, 2, 14, 0, 0, 0, 0))) + self.assertEqual(after_board, ScheduleBoard.get_current(datetime.datetime(2014, 2, 15, 0, 0, 0, 0))) + self.assertEqual(after_board, ScheduleBoard.get_current(datetime.datetime(2014, 6, 1, 0, 0, 0, 0))) def test_validation_exception_1(self): schedule_board = ScheduleBoard.objects.create( From 108ee6fbeed043da5e438b1381a11c6affb5b5b1 Mon Sep 17 00:00:00 2001 From: Stefan Date: Mon, 7 Mar 2016 09:25:47 +0100 Subject: [PATCH 5/5] fix redundant brackets for long ifs --- radio/apps/schedules/models.py | 9 ++++----- 1 file changed, 4 insertions(+), 5 deletions(-) diff --git a/radio/apps/schedules/models.py b/radio/apps/schedules/models.py index 36cda85..bcab90e 100755 --- a/radio/apps/schedules/models.py +++ b/radio/apps/schedules/models.py @@ -91,7 +91,7 @@ def save(self, *args, **kwargs): # rearrange episodes if self.pk is not None: orig = ScheduleBoard.objects.get(pk=self.pk) - if (orig.start_date != self.start_date or orig.end_date != self.end_date): # Field has changed + if orig.start_date != self.start_date or orig.end_date != self.end_date: # Field has changed super(ScheduleBoard, self).save(*args, **kwargs) Episode.rearrange_episodes(programme=None, after=datetime.datetime.now()) else: @@ -136,11 +136,11 @@ def runtime(self): def __get_rrule(self): start_date = self.programme.start_date - if (self.schedule_board.start_date and start_date < self.schedule_board.start_date): + if self.schedule_board.start_date and start_date < self.schedule_board.start_date: start_date = self.schedule_board.start_date if self.programme.end_date: end_date = self.programme.end_date - if (self.schedule_board.end_date and end_date > self.schedule_board.end_date): + if self.schedule_board.end_date and end_date > self.schedule_board.end_date: end_date = self.schedule_board.end_date # Due to rrule we need to add 1 day end_date = end_date + datetime.timedelta(days=1) @@ -210,7 +210,6 @@ def clean(self): end_date=end_date.strftime("%H:%M %d/%m/%Y") ) ) - index += 1 def save(self, *args, **kwargs): @@ -266,7 +265,7 @@ def schedule(cls, dt, exclude=None): if date and (earlier_date is None or date > earlier_date): earlier_date = date earlier_schedule = schedule - if (earlier_schedule is None or dt > earlier_date + earlier_schedule.runtime()): # Todo: check + if earlier_schedule is None or dt > earlier_date + earlier_schedule.runtime(): # Todo: check return None, None return earlier_schedule, earlier_date