def test_rearrange_episodes_new_schedule(self): # Next calendar shouldn't appear due to doesn't belong to the active calendar Schedule.objects.create( programme=self.programme, calendar=Calendar.objects.create(), type="L", start_dt=utc.localize(datetime.datetime(2015, 1, 3, 16, 0, 0)), recurrences=recurrence.Recurrence( rrules=[recurrence.Rule(recurrence.WEEKLY)])) Schedule.objects.create( programme=self.programme, calendar=self.calendar, type="L", start_dt=utc.localize(datetime.datetime(2015, 1, 3, 17, 0, 0)), recurrences=recurrence.Recurrence( rrules=[recurrence.Rule(recurrence.WEEKLY)])) # save should call rearrange # rearrange_programme_episodes(self.programme, pytz.utc.localize(datetime.datetime(2015, 1, 1))) self.assertListEqual( [ e.issue_date for e in self.programme.episode_set.all().order_by('issue_date')[:5] ], [ utc.localize(datetime.datetime(2015, 1, 1, 14, 0)), utc.localize(datetime.datetime(2015, 1, 2, 14, 0)), utc.localize(datetime.datetime(2015, 1, 3, 14, 0)), # The next schedule doesn't belong to the active_calendar # utc.localize(datetime.datetime(2015, 1, 3, 16, 0)), utc.localize(datetime.datetime(2015, 1, 3, 17, 0)), utc.localize(datetime.datetime(2015, 1, 4, 14, 0)), ])
def make_expired_daily_reccurence(self): rule = recurrence.Rule(recurrence.DAILY) return recurrence.Recurrence( dtstart=timezone.now() - timedelta(days=10), dtend=timezone.now() - timedelta(days=1), rrules=[rule] )
def test_complete_task_monthly_recurrence(self): myrule = recurrence.Rule(recurrence.MONTHLY, bymonthday=[1]) pattern = recurrence.Recurrence(dtstart=datetime(2014, 1, 2, 0, 0, 0), dtend=datetime(2150, 1, 3, 0, 0, 0), rrules=[ myrule, ]) start_at = timezone.make_aware(datetime(2017, 1, 1, 7, 0, 0)) due_at = timezone.make_aware(datetime(2017, 1, 1, 10, 0, 0)) next_start_at = start_at + timedelta(days=31) next_due_at = due_at + timedelta(days=31) action = Action.objects.create(owner=self.user, short_description="Test Action", recurrence=pattern, start_at=start_at, due_at=due_at, context=self.user.context_set.first(), folder=self.user.folder_set.first()) action.save() self.assertIs(action.status, action.STATUS_OPEN) action.status = action.STATUS_COMPLETED action.save() self.assertIs(action.status, action.STATUS_OPEN) action_recurrence = ActionRecurrence.objects.get(action=action) self.assertIs(action_recurrence.action.id, action.id) self.assertIs(action_recurrence.status, action.STATUS_COMPLETED) self.assertEqual(action_recurrence.start_at, start_at) self.assertEqual(action_recurrence.due_at, due_at) self.assertEqual(action.start_at, next_start_at) self.assertEqual(action.due_at, next_due_at) self.assertEqual(action.completed_at, None)
def setUp(self): self.calendar = Calendar.objects.create(name='Calendar', is_active=True) self.recurrences = recurrence.Recurrence(rrules=[ recurrence.Rule(recurrence.WEEKLY, until=utc.localize(datetime.datetime(2014, 1, 31))) ]) programme = Programme.objects.filter(name="Classic hits").get() programme.name = "Classic hits 2" programme.slug = None programme.id = programme.pk = None programme.save() self.programme = programme self.schedule = Schedule.objects.create( programme=self.programme, type='L', recurrences=self.recurrences, start_dt=utc.localize(datetime.datetime(2014, 1, 6, 14, 0, 0)), calendar=self.calendar) self.episode = Episode.objects.create( title='Episode 1', programme=programme, summary='', season=1, number_in_season=1, ) self.programme.rearrange_episodes( pytz.utc.localize(datetime.datetime(1970, 1, 1)), Calendar.get_active()) self.episode.refresh_from_db()
def setUp(self): self.manager = CalendarManager() programme = Programme.objects.filter(name="Classic hits").get() programme.name = "Classic hits - ScheduleUtilsTests" programme.slug = None programme.id = programme.pk = None programme.save() self.programme = programme Schedule.objects.get_or_create( programme=programme, type='L', calendar=self.calendar, recurrences=recurrence.Recurrence( rrules=[recurrence.Rule(recurrence.DAILY)]), start_dt=pytz.utc.localize(datetime.datetime(2015, 1, 1, 14, 0, 0))) for number in range(1, 11): Episode.objects.create( title='Episode %s' % number, programme=programme, summary='', season=1, number_in_season=number, ) programme.rearrange_episodes( pytz.utc.localize(datetime.datetime(1970, 1, 1)), Calendar.get_active())
def test_complete_task_ended_recurrence(self): myrule = recurrence.Rule(freq=recurrence.DAILY, dtstart=datetime(2014, 1, 2, 0, 0, 0), dtend=datetime(2015, 1, 2, 0, 0, 0), interval=1, count=1) pattern = recurrence.Recurrence(rrules=[ myrule, ]) start_at = timezone.make_aware(datetime(2018, 1, 15, 4, 0, 0)) due_at = timezone.make_aware(datetime(2018, 1, 15, 12, 0, 0)) action = Action.objects.create(owner=self.user, short_description="Test Action", recurrence=pattern, start_at=start_at, due_at=due_at, context=self.user.context_set.first(), folder=self.user.folder_set.first()) action.save() self.assertIs(action.status, action.STATUS_OPEN) action.status = action.STATUS_COMPLETED action.save() self.assertIs(action.status, action.STATUS_COMPLETED) action_recurrence = ActionRecurrence.objects.get(action=action) self.assertIs(action_recurrence.action.id, action.id) self.assertIs(action_recurrence.status, action.STATUS_COMPLETED) self.assertEqual(action_recurrence.start_at, start_at) self.assertEqual(action_recurrence.due_at, due_at) self.assertEqual(action.completed_at, timezone.make_aware(datetime.now()))
def get_recurrence_rrule(self): r = recurrence.Recurrence(dtstart=self.start_date, dtend=datetime(2014, 1, 3, 0, 0, 0), rrules=[ recurrence.Rule(recurrence.WEEKLY), ]) return r
def put(self, request, *args, **kwargs): team_info = json.loads(request.body.decode('utf-8')) validator = Validator(team_schema) if not validator.validate(team_info): return JsonResponse({'error': validator.errors}) try: team = Team.objects.get(id=int(self.kwargs['team_id'])) except ObjectDoesNotExist: return JsonResponse({'error': [{"Team ID": "Team not found for ID in request"}]}) check_scope(request, team) report = team.report_set.first() if 'send_time' in team_info: report.survey_send_time = parser.parse(team_info['send_time']).replace(second=0, microsecond=0) if 'summary_time' in team_info: report.summary_send_time = parser.parse(team_info['summary_time']).replace(second=0, microsecond=0) if 'days_of_week' in team_info: rule = recurrence.Rule(recurrence.WEEKLY, byday=team_info['days_of_week']) rec = recurrence.Recurrence(rrules=[rule]) report.recurrences = rec if 'name' in team_info: team.name = team_info['name'] report.save() try: team.save() except IntegrityError: return JsonResponse({'error': {"name": _("team with this name already exists")}}) team_dict = model_to_dict(team, exclude=['users']) team_dict['report'] = self.report_dict(team) return JsonResponse({'team': team_dict})
def setUp(self): all_days_but_today = list(range(7)) all_days_but_today.remove(datetime.today().weekday()) rule_not = recurrence.Rule(recurrence.WEEKLY, byday=all_days_but_today) rec_not = recurrence.Recurrence(rrules=[rule_not]) self.admin = User.objects.create(email="*****@*****.**", username="******") self.team = Team.objects.create(name="celery_team_test", admin=self.admin) self.report_not_today = Report.objects.create( team=self.team, recurrences=rec_not, survey_send_time=time.min) self.report = Report.objects.create( team=self.team, survey_send_time=time.min, recurrences=recurrence.Recurrence( rrules=[recurrence.Rule(recurrence.WEEKLY, byday=range(7))]))
def test_create_monthly(client, income_series): rule = recurrence.Rule(recurrence.MONTHLY, bymonthday=17, until=datetime(2021, 10, 17, 0, 0)) post_data = { 'budgeted_amount': 100.0, 'budgeted_date': datetime(2020, 10, 20, 0, 0).date(), 'description': 'hundred bucks worth of whipped cream', 'recurrences': recurrence.serialize(rule), } response = client.post(reverse('create-expense'), post_data) assert response.status_code == 302 assert response.url == '/' assert Expense.objects.count() == 11 assert Expense.objects.filter(budgeted_date='2020-10-20').first() == None incomes = Income.objects.filter(expense__isnull=False) assert incomes.count() == 11 for income in incomes: previous_income = income.get_previous_by_budgeted_date() assert income.carry_over == (previous_income.income - abs( previous_income.total_expenses)) + previous_income.carry_over
class Migration(migrations.Migration): dependencies = [ ('schedules', '0001_initial'), ] operations = [ migrations.AddField( model_name='schedule', name='recurrences', field=recurrence.fields.RecurrenceField( default=recurrence.Recurrence( rrules=[recurrence.Rule(recurrence.WEEKLY)]), verbose_name='recurrences'), preserve_default=False, ), migrations.RunPython(migrate_schedules), migrations.RemoveField( model_name='schedule', name='day', ), migrations.RemoveField( model_name='schedule', name='start_hour', ), ]
def setUp(self): self.url = "/pending/" self.client = Client() self.pending_event = factory.event( approval_status=constants.EventApprovalStatus.PENDING.name, recurrences=recurrence.Recurrence(rrules=[recurrence.Rule(recurrence.DAILY)]), ) self.pending_event.save()
def test_should_generate_proper_recurrence_rules(self): """ Basically it's not a regular test, but short tip-list about how RRules being serialized """ # Every day r = recurrence.Rule(recurrence.DAILY) assert serialize(r) == 'RRULE:FREQ=DAILY' # Every second day r = recurrence.Rule(recurrence.DAILY, interval=2) assert serialize(r) == 'RRULE:FREQ=DAILY;INTERVAL=2' # Every week r = recurrence.Rule(recurrence.WEEKLY) assert serialize(r) == 'RRULE:FREQ=WEEKLY' # Every second week r = recurrence.Rule(recurrence.WEEKLY, interval=2) assert serialize(r) == 'RRULE:FREQ=WEEKLY;INTERVAL=2' # Every second week on Wednesdays r = recurrence.Rule(recurrence.WEEKLY, interval=2, byday=2) assert serialize(r) == 'RRULE:FREQ=WEEKLY;INTERVAL=2;BYDAY=WE' # Every month on 11th day r = recurrence.Rule(recurrence.MONTHLY, interval=1, bymonthday=11) assert serialize(r) == 'RRULE:FREQ=MONTHLY;BYMONTHDAY=11' # Every month on second Sunday r = recurrence.Rule(recurrence.MONTHLY, interval=1, byday=6, bysetpos=2) assert serialize(r) == 'RRULE:FREQ=MONTHLY;BYDAY=SU;BYSETPOS=2' # Every year on 11th of July r = recurrence.Rule(recurrence.YEARLY, interval=1, bymonth=recurrence.JULY, bymonthday=11) assert serialize(r) == 'RRULE:FREQ=YEARLY;BYMONTH=7;BYMONTHDAY=11' # Every second Sunday of June r = recurrence.Rule(recurrence.YEARLY, interval=1, bymonth=recurrence.JUNE, byday=6, bysetpos=2) assert serialize( r) == 'RRULE:FREQ=YEARLY;BYDAY=SU;BYSETPOS=2;BYMONTH=6'
def test_run_review_notices(self): self.notice.recurrences = recurrence.Recurrence( rrules=[recurrence.Rule(recurrence.DAILY)]) self.notice.time = (timezone.localtime(timezone.now()) + timezone.timedelta(minutes=1)).time() self.notice.save() tasks.run_review_notices() assert Schedule.objects.count() == 1
def biweekly(five_this_morning): today = five_this_morning.weekday() next_year = five_this_morning.year + 1 end_date = five_this_morning.replace(year=next_year) return recurrence.Rule(recurrence.WEEKLY, interval=2, byday=today, until=end_date)
def setUp(self): self.recurrences = recurrence.Recurrence( dtstart=datetime.datetime(2014, 1, 6, 14, 0, 0), dtend=datetime.datetime(2014, 1, 31, 14, 0, 0), rrules=[recurrence.Rule(recurrence.WEEKLY)]) self.schedule = Schedule.objects.create(slot=self.slot, type='L', recurrences=self.recurrences)
def monthly(five_this_morning): today = five_this_morning.day next_year = five_this_morning.year + 1 end_date = five_this_morning.replace(year=next_year) return recurrence.Rule(recurrence.MONTHLY, interval=1, bymonthday=today, until=end_date)
def setUpTestData(cls): calendar, created = Calendar.objects.get_or_create(name='Example', is_active=True) admin_user = User.objects.create_superuser(username='******', email='*****@*****.**', password='******') cls.recorder_programme, created = Programme.objects.get_or_create( name='Recorder me', defaults={ u'synopsis': u'synopsis', u'language': u'en', u'photo': u'defaults/example/radio_5.jpg', u'current_season': 3, u'category': u'News & Politics', u'_runtime': 60 }) cls.recorder_schedule, created = Schedule.objects.get_or_create( programme=cls.recorder_programme, type='L', calendar=calendar, recurrences=recurrence.Recurrence( rrules=[recurrence.Rule(recurrence.DAILY)]), start_dt=pytz.utc.localize(datetime.datetime(2015, 1, 1, 14, 0, 0))) Schedule.objects.get_or_create( programme=cls.recorder_programme, type='B', calendar=calendar, recurrences=recurrence.Recurrence( rrules=[recurrence.Rule(recurrence.DAILY)]), start_dt=pytz.utc.localize(datetime.datetime(2015, 1, 1, 18, 0, 0))) Episode.objects.get_or_create(title='Episode 2x1', programme=cls.recorder_programme, summary="summary", season=2, number_in_season=1, issue_date=pytz.utc.localize( datetime.datetime( 2015, 1, 1, 14, 0, 0)))
def test_between_time_change_skip(self): schedule = Schedule(slot=self.slot, recurrences=recurrence.Recurrence( dtstart=datetime.datetime( 2018, 3, 24, 2, 30, 0), rrules=[recurrence.Rule(recurrence.DAILY)])) between = Transmission.between(datetime.datetime(2018, 3, 25, 0, 0, 0), datetime.datetime(2018, 3, 25, 5, 0, 0), schedules=[schedule]) self.assertEqual(list(between), [])
def create_freq_schedule(apps, schema): Frequency = apps.get_model("qa", "Frequency") from_ = timezone.datetime(2012, 1, 1, tzinfo=timezone.get_current_timezone()) for f in Frequency.objects.all(): rule = recurrence.Rule(recurrence.DAILY, interval=f.due_interval) f.recurrences = recurrence.Recurrence(rrules=[rule], dtstart=from_) f.overdue_interval = max(1, f.overdue_interval - f.nominal_interval) f.nominal_interval = calc_nominal_interval(f) f.save()
def test_dates_between_complex_ruleset(self): schedule = Schedule( slot=Slot(runtime=datetime.timedelta(minutes=60)), recurrences=recurrence.Recurrence( dtstart=datetime.datetime(2014, 1, 2, 14, 0, 0), rrules=[recurrence.Rule(recurrence.DAILY, interval=2)], exrules=[ recurrence.Rule(recurrence.WEEKLY, byday=[recurrence.MO, recurrence.TU]) ])) self.assertListEqual( list( schedule.dates_between(datetime.datetime(2014, 1, 1), datetime.datetime(2014, 1, 9))), [ timezone.make_aware(datetime.datetime(2014, 1, 2, 14, 0)), timezone.make_aware(datetime.datetime(2014, 1, 4, 14, 0)), timezone.make_aware(datetime.datetime(2014, 1, 8, 14, 0)) ])
def test_complex_rule_serialization_with_weekday_instance(self): rule = recurrence.Rule( recurrence.WEEKLY, interval=17, wkst=recurrence.to_weekday(1), count=7, byday=[recurrence.to_weekday('-1MO'), recurrence.to_weekday('TU')], bymonth=[1, 3]) vrecurr = utils.build_rrule_from_recurrences_rrule(rule) assert vRecur(vrecurr).to_ical().decode( ) == 'FREQ=WEEKLY;COUNT=7;INTERVAL=17;BYDAY=-1MO,TU;BYMONTH=1,3;WKST=TU'
def test_create_from_recurrence_object(): inrule = recurrence.Rule(recurrence.WEEKLY) exrule = recurrence.Rule(recurrence.MONTHLY) limits = recurrence.Recurrence( dtstart=datetime(2014, 1, 1, 0, 0, 0), dtend=datetime(2014, 2, 3, 0, 0, 0), rrules=[inrule], exrules=[exrule], rdates=[datetime(2014, 2, 15, 0, 0, 0)], exdates=[aware(datetime(2014, 11, 29, 0, 0, 0))]) object = Recurrence.objects.create_from_recurrence_object(limits) assert object.dtstart == aware(datetime(2014, 1, 1, 0, 0, 0)) assert object.dtend == aware(datetime(2014, 2, 3, 0, 0, 0)) rules = object.rules.all() assert len(rules) == 2 in_rules = [r for r in rules if r.mode == choices.INCLUSION] out_rules = [r for r in rules if r.mode == choices.EXCLUSION] assert len(in_rules) == 1 assert len(out_rules) == 1 assert in_rules[0].freq == recurrence.WEEKLY assert out_rules[0].freq == recurrence.MONTHLY dates = object.dates.all() assert len(dates) == 2 in_dates = [d for d in dates if d.mode == choices.INCLUSION] out_dates = [d for d in dates if d.mode == choices.EXCLUSION] assert len(in_dates) == 1 assert len(out_dates) == 1 assert in_dates[0].dt == aware(datetime(2014, 2, 15, 0, 0, 0)) assert out_dates[0].dt == aware(datetime(2014, 11, 29, 0, 0, 0))
def test_impossible_recurrence_after(self): """ Testing error calling after and function wrapper to solve it (recurrence_after) """ start_dt = datetime.datetime(2014, 1, 20, 14, 0, 0) until_dt = datetime.datetime(2014, 1, 19, 14, 0, 0) daily_recurrence = recurrence.Recurrence( rrules=[recurrence.Rule(recurrence.DAILY, until=until_dt)]) dt = daily_recurrence.after(start_dt, True, dtstart=start_dt) self.assertEqual(start_dt, dt) # wrong! self.assertIsNone( recurrence_after(daily_recurrence, start_dt, start_dt))
def setUp(self): rule = recurrence.Rule(recurrence.WEEKLY, byday=range(7)) rec = recurrence.Recurrence(rrules=[rule]) self.admin = User.objects.create(email="*****@*****.**", username="******") self.team = Team.objects.create(name="celery_team_test", admin=self.admin) self.membership = Membership.objects.create(team=self.team, user=self.admin) self.report = Report.objects.create(team=self.team, recurrences=rec, survey_send_time=time.min) self.question = Question.objects.create(report=self.report, text='test')
def test_recurring_event(self): """Given a recurring event, Google Calendar payload contains recurrence""" event = factory.event(recurrences=recurrence.Recurrence(rrules=[recurrence.Rule(recurrence.DAILY)])) event.save() with mock.patch('census.google_calendar.get_service', return_value=self.mock_service): google_calendar.google_publish_event(event) self.mock_service.events.assert_called_with() self.mock_events.insert.assert_called_once() payload = self.mock_events.insert.call_args[1]['body'] self.assertEqual(payload['recurrence'], ['RRULE:FREQ=DAILY'])
def setUp(self): synopsis = ''' This programme has complex schedules to test timezone changes. Only active between March and October 2017 ''' programme, created = Programme.objects.get_or_create( name='Timezone', defaults={ 'synopsis': synopsis, 'language': 'en', 'photo': 'defaults/example/radio_1.jpg', 'current_season': 1, 'category': 'News & Politics', '_runtime': 60, 'start_date': datetime.date(2017, 3, 1), 'end_date': datetime.date(2017, 10, 31), }) self.cest_schedule, created = Schedule.objects.get_or_create( programme=programme, type='L', calendar=self.calendar, recurrences=recurrence.Recurrence(rrules=[ recurrence.Rule(recurrence.DAILY, until=SPAIN_TZ.localize( datetime.datetime(2017, 3, 27))) ]), start_dt=SPAIN_TZ.localize( datetime.datetime(2017, 3, 25, 10, 00, 00))) self.cet_schedule, created = Schedule.objects.get_or_create( programme=programme, type='L', calendar=self.calendar, recurrences=recurrence.Recurrence( rrules=[recurrence.Rule(recurrence.DAILY)], ), start_dt=SPAIN_TZ.localize( datetime.datetime(2017, 10, 28, 14, 00, 00)))
def test_dates_between_complex_ruleset(self): programme = Programme.objects.create(name="Programme 14:00 - 15:00", current_season=1, runtime=60) schedule = Schedule.objects.create( programme=programme, calendar=self.calendar, start_dt=utc.localize(datetime.datetime(2014, 1, 2, 14, 0, 0)), recurrences=recurrence.Recurrence( rrules=[recurrence.Rule(recurrence.DAILY, interval=2)], exrules=[ recurrence.Rule(recurrence.WEEKLY, byday=[recurrence.MO, recurrence.TU]) ])) self.assertCountEqual( schedule.dates_between(utc.localize(datetime.datetime(2014, 1, 1)), utc.localize(datetime.datetime(2014, 1, 9))), [ utc.localize(datetime.datetime(2014, 1, 2, 14, 0)), utc.localize(datetime.datetime(2014, 1, 4, 14, 0)), utc.localize(datetime.datetime(2014, 1, 8, 14, 0)) ])
def day_of_month(self, day=1): """Generate a frequency to be performed on the specific day of month with a 7 day window_start and 7 day window_end""" rule = recurrence.Rule(freq=recurrence.MONTHLY, bymonthday=day) return models.Frequency( name="Day of Month", slug="day-of-month", recurrences=recurrence.Recurrence( rrules=[rule], dtstart=timezone.datetime(2012, 1, 1, tzinfo=timezone.utc), ), window_end=7, window_start=7, )
def n_weekly(self, weeks=4): """Generate a frequency to be performed on the specific day of month with a 7 day window_start and 7 day window_end""" rule = recurrence.Rule(freq=recurrence.WEEKLY, interval=weeks) return models.Frequency( name="%s weekly" % weeks, slug="%s-weekly" % weeks, recurrences=recurrence.Recurrence( rrules=[rule], dtstart=timezone.datetime(2012, 1, 1, tzinfo=timezone.utc), ), window_end=7, window_start=7, )