예제 #1
0
def test_check_allowable_frequencies():
    rule = Rule(
        recurrence.WEEKLY
    )

    limits = Recurrence(
        rrules=[rule]
    )

    value = recurrence.serialize(limits)

    field = RecurrenceField(frequencies=[
        recurrence.WEEKLY
    ])
    field.clean(value)

    field = RecurrenceField(frequencies=[
        recurrence.YEARLY
    ])
    with pytest.raises(forms.ValidationError) as e:
        field.clean(value)
    assert e.value.messages[0] == "Invalid frequency."

    limits = Recurrence(
        exrules=[rule]
    )

    value = recurrence.serialize(limits)

    with pytest.raises(forms.ValidationError) as e:
        field.clean(value)
    assert e.value.messages[0] == "Invalid frequency."
def test_create_from_rule_object_bymonth():
    limits = Recurrence.objects.create()
    rule = Rule.objects.create(
        recurrence=limits,
        mode=choices.INCLUSION,
        freq=recurrence.WEEKLY,
        until=make_aware(datetime(2014, 12, 31, 0, 0, 0), pytz.utc)
    )
    Param.objects.create(
        rule=rule,
        param='bymonth',
        value=6,
        index=0
    )
    Param.objects.create(
        rule=rule,
        param='bymonth',
        value=8,
        index=1
    )

    expected = 'RRULE:FREQ=WEEKLY;UNTIL=20141231T000000Z;BYMONTH=6,8'

    original = Rule.objects.to_rule_object(rule)
    serialized = recurrence.serialize(original)
    assert serialized == expected

    object = Rule.objects.create_from_rule_object(
        choices.INCLUSION,
        original,
        limits
    )

    serialized = recurrence.serialize(object.to_rule_object())
    assert serialized == expected
def test_check_allowable_frequencies():
    rule = Rule(
        recurrence.WEEKLY
    )

    limits = Recurrence(
        rrules=[rule]
    )

    value = recurrence.serialize(limits)

    field = RecurrenceField(frequencies=[
        recurrence.WEEKLY
    ])
    field.clean(value)

    field = RecurrenceField(frequencies=[
        recurrence.YEARLY
    ])
    with pytest.raises(forms.ValidationError) as e:
        field.clean(value)
    assert e.value.messages[0] == "Invalid frequency."

    limits = Recurrence(
        exrules=[rule]
    )

    value = recurrence.serialize(limits)

    with pytest.raises(forms.ValidationError) as e:
        field.clean(value)
    assert e.value.messages[0] == "Invalid frequency."
예제 #4
0
파일: test_income.py 프로젝트: evz/cream
def test_update_relations(client, biweekly, five_this_morning):
    budgeted_date = (five_this_morning - timedelta(days=1)).date()
    start_date = five_this_morning.date()

    first_occurrence = Income.objects.create(
        budgeted=1000.0,
        budgeted_date=budgeted_date,
        recurrences=recurrence.serialize(biweekly))
    updater = UpdateIncomeRelationsMixin()
    updater.object = first_occurrence

    updater.update_relations(update_series=True)

    assert Income.objects.count() == 27
    assert Income.objects.order_by(
        'budgeted_date').first().budgeted_date == start_date

    somewhere_in_the_middle = Income.objects.all()[10]

    new_start_date = datetime.combine(somewhere_in_the_middle.budgeted_date,
                                      datetime.min.time())

    new_recurrence = recurrence.Recurrence(dtstart=new_start_date,
                                           include_dtstart=False,
                                           rrules=[biweekly])

    post_data = {
        'budgeted': 1500.0,
        'budgeted_date': somewhere_in_the_middle.budgeted_date,
        'update_all': 'Yes',
        'recurrences': recurrence.serialize(new_recurrence),
        'first_occurrence': somewhere_in_the_middle.first_occurrence.id,
    }

    response = client.post(
        reverse('update-income', args=(somewhere_in_the_middle.id, )),
        post_data)

    assert response.status_code == 302

    thousands = Income.objects.filter(budgeted=1000.0)
    fifteens = Income.objects.filter(budgeted=1500.0)

    assert thousands.count() == 10
    assert fifteens.count() == 17
    assert first_occurrence.income_set.count() == 9
    assert len(set(i.budgeted_date
                   for i in Income.objects.all())) == Income.objects.count()
예제 #5
0
def test_include_dtstart_from_field():
    rule = Rule(
        recurrence.WEEKLY,
        byday=recurrence.MONDAY
    )

    limits = Recurrence(
        rrules=[rule]
    )

    value = recurrence.serialize(limits)

    model_field = recurrence.fields.RecurrenceField()  # Test with include_dtstart=True (default)
    rec_obj = model_field.to_python(value)
    assert rec_obj == limits
    # 2nd of August (dtstart) is expected but only for inc=True
    assert rec_obj.between(datetime(2015, 8, 2), datetime(2015, 8, 11), inc=True, dtstart=datetime(2015, 8, 2)) == [
        datetime(2015, 8, 2, 0, 0), datetime(2015, 8, 3, 0, 0), datetime(2015, 8, 10, 0, 0)]
    assert rec_obj.between(datetime(2015, 8, 2), datetime(2015, 8, 11), inc=False, dtstart=datetime(2015, 8, 2)) == [
        datetime(2015, 8, 3, 0, 0), datetime(2015, 8, 10, 0, 0)]

    model_field = recurrence.fields.RecurrenceField(include_dtstart=False)  # Test with include_dtstart=False
    rec_obj = model_field.to_python(value)
    assert rec_obj == limits
    # 2nd of August (dtstart) is not expected regardless of inc
    assert rec_obj.between(datetime(2015, 8, 2), datetime(2015, 8, 11), inc=True, dtstart=datetime(2015, 8, 2)) == [
        datetime(2015, 8, 3, 0, 0), datetime(2015, 8, 10, 0, 0)]
    assert rec_obj.between(datetime(2015, 8, 2), datetime(2015, 8, 11), inc=False, dtstart=datetime(2015, 8, 2)) == [
        datetime(2015, 8, 3, 0, 0), datetime(2015, 8, 10, 0, 0)]
예제 #6
0
파일: test_expense.py 프로젝트: evz/cream
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
def test_include_dtstart_from_field():
    rule = Rule(
        recurrence.WEEKLY,
        byday=recurrence.MONDAY
    )

    limits = Recurrence(
        rrules=[rule]
    )

    value = recurrence.serialize(limits)

    model_field = recurrence.fields.RecurrenceField()  # Test with include_dtstart=True (default)
    rec_obj = model_field.to_python(value)
    assert rec_obj == limits
    # 2nd of August (dtstart) is expected but only for inc=True
    assert rec_obj.between(datetime(2015, 8, 2), datetime(2015, 8, 11), inc=True, dtstart=datetime(2015, 8, 2)) == [
        datetime(2015, 8, 2, 0, 0), datetime(2015, 8, 3, 0, 0), datetime(2015, 8, 10, 0, 0)]
    assert rec_obj.between(datetime(2015, 8, 2), datetime(2015, 8, 11), inc=False, dtstart=datetime(2015, 8, 2)) == [
        datetime(2015, 8, 3, 0, 0), datetime(2015, 8, 10, 0, 0)]

    model_field = recurrence.fields.RecurrenceField(include_dtstart=False)  # Test with include_dtstart=False
    rec_obj = model_field.to_python(value)
    assert rec_obj == limits
    # 2nd of August (dtstart) is not expected regardless of inc
    assert rec_obj.between(datetime(2015, 8, 2), datetime(2015, 8, 11), inc=True, dtstart=datetime(2015, 8, 2)) == [
        datetime(2015, 8, 3, 0, 0), datetime(2015, 8, 10, 0, 0)]
    assert rec_obj.between(datetime(2015, 8, 2), datetime(2015, 8, 11), inc=False, dtstart=datetime(2015, 8, 2)) == [
        datetime(2015, 8, 3, 0, 0), datetime(2015, 8, 10, 0, 0)]
    def test_strip_dtstart_and_dtend_if_required(self):
        """Test that naive datetimes will get converted to UTC and returned as UTC."""
        rule = Rule(
            recurrence.WEEKLY
        )

        limits = Recurrence(
            dtstart=datetime(2014, 1, 1, 0, 0, 0),
            dtend=datetime(2014, 2, 3, 0, 0, 0),
            rrules=[rule]
        )

        value = recurrence.serialize(limits)

        field = RecurrenceField()
        cleaned_value = field.clean(value)
        assert cleaned_value.rrules == [rule]
        assert cleaned_value.dtstart == datetime(2014, 1, 1, 0, 0, 0, tzinfo=pytz.utc)
        assert cleaned_value.dtend == datetime(2014, 2, 3, 0, 0, 0, tzinfo=pytz.utc)

        field = RecurrenceField(accept_dtstart=False, accept_dtend=False)
        cleaned_value = field.clean(value)
        assert cleaned_value != limits
        assert cleaned_value.dtstart is None
        assert cleaned_value.dtend is None
예제 #9
0
    def test_strip_dtstart_and_dtend_if_required(self):
        """Test that naive datetimes will get converted to UTC and returned as UTC."""
        rule = Rule(recurrence.WEEKLY)

        limits = Recurrence(dtstart=datetime(2014, 1, 1, 0, 0, 0),
                            dtend=datetime(2014, 2, 3, 0, 0, 0),
                            rrules=[rule])

        value = recurrence.serialize(limits)

        field = RecurrenceField()
        cleaned_value = field.clean(value)
        assert cleaned_value.rrules == [rule]
        assert cleaned_value.dtstart == datetime(2014,
                                                 1,
                                                 1,
                                                 0,
                                                 0,
                                                 0,
                                                 tzinfo=pytz.utc)
        assert cleaned_value.dtend == datetime(2014,
                                               2,
                                               3,
                                               0,
                                               0,
                                               0,
                                               tzinfo=pytz.utc)

        field = RecurrenceField(accept_dtstart=False, accept_dtend=False)
        cleaned_value = field.clean(value)
        assert cleaned_value != limits
        assert cleaned_value.dtstart is None
        assert cleaned_value.dtend is None
예제 #10
0
    def test_dt_start_and_dtend_converts_to_utc(self):
        """Convert the values for dtstart and dtend to UTC."""
        tz = pytz.timezone('America/Adak')

        limits = Recurrence(
            dtstart=datetime(2014, 1, 1, 0, 0, 0, tzinfo=tz),
            dtend=datetime(2014, 2, 3, 0, 0, 0, tzinfo=tz),
        )

        value = recurrence.serialize(limits)

        field = RecurrenceField()
        cleaned_value = field.clean(value)
        assert cleaned_value.dtstart == datetime(2014,
                                                 1,
                                                 1,
                                                 0,
                                                 0,
                                                 0,
                                                 tzinfo=tz).astimezone(
                                                     pytz.utc)
        assert cleaned_value.dtend == datetime(2014, 2, 3, 0, 0, 0,
                                               tzinfo=tz).astimezone(pytz.utc)
        assert cleaned_value.dtstart.tzname() == 'UTC'
        assert cleaned_value.dtend.tzname() == 'UTC'
예제 #11
0
파일: test_expense.py 프로젝트: evz/cream
def test_update_expense(client, five_this_morning, income_series):
    expense = Expense.objects.create(
        budgeted_date=five_this_morning.date(),
        budgeted_amount=100.0,
        description='hundred bucks worth of twinkies',
        recurrences='RDATE:{}'.format(
            five_this_morning.strftime('%Y%m%dT050000Z')),
        income=income_series[0])

    response = client.get(reverse('update-expense', args=(expense.id, )))

    assert response.status_code == 200

    tomorrow_morning = five_this_morning + timedelta(days=1)
    end_date = tomorrow_morning + timedelta(days=365)

    rule = recurrence.Rule(recurrence.MONTHLY,
                           interval=1,
                           bymonthday=tomorrow_morning.day,
                           until=end_date)

    post_data = {
        'budgeted_amount': 150.0,
        'budgeted_date': tomorrow_morning.date(),
        'description': 'hundred bucks worth of twinkies',
        'recurrences': recurrence.serialize(rule),
        'income': income_series[0].id,
        'update_all': 'Yes',
    }

    response = client.post(reverse('update-expense', args=(expense.id, )),
                           post_data)

    expense = Expense.objects.get(id=expense.id)

    assert response.status_code == 302
    assert response.url == reverse('income-detail',
                                   args=(expense.income.slug, ))

    assert set(recurrence.serialize(r)
               for r in expense.recurrences.rrules) == set(
                   [recurrence.serialize(rule)])

    assert Expense.objects.count() == 12

    for expense in Expense.objects.all():
        assert expense.income in income_series
예제 #12
0
 def test_aware_until_gets_converted_to_utc(self):
     tz = pytz.timezone('America/Adak')
     until = datetime(2014, 1, 1, 0, 0, 0, tzinfo=tz)
     recurs = Recurrence(rrules=[Rule(recurrence.DAILY, until=until)], )
     value = recurrence.serialize(recurs)
     field = RecurrenceField()
     cleaned_value = field.clean(value)
     assert cleaned_value.rrules[0].until == until.astimezone(pytz.utc)
    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'
예제 #14
0
def test_rule_serialization():
    rule = Rule(
        recurrence.WEEKLY
    )

    serialized = recurrence.serialize(rule)
    assert 'RRULE:FREQ=WEEKLY' == serialized
    assert recurrence.deserialize(serialized) == Recurrence(rrules=[rule])
def test_rule_serialization():
    rule = Rule(
        recurrence.WEEKLY
    )

    serialized = recurrence.serialize(rule)
    assert 'RRULE:FREQ=WEEKLY' == serialized
    assert recurrence.deserialize(serialized) == Recurrence(rrules=[rule])
예제 #16
0
    def get_db_prep_value(self, value, connection=None, prepared=False):
        if value is None and self.null == False:
            raise ValueError(
                'Cannot assign None: "%s.%s" does not allow null values.' %
                (self.model._meta.object_name, self.name))

        if isinstance(value, basestring):
            value = recurrence.deserialize(value)
        return recurrence.serialize(value)
예제 #17
0
    def get_db_prep_value(self, value, connection=None, prepared=False):
        if value is None and self.null == False:
            raise ValueError(
                'Cannot assign None: "%s.%s" does not allow null values.' % (
                self.model._meta.object_name, self.name))

        if isinstance(value, basestring):
            value = recurrence.deserialize(value)
        return recurrence.serialize(value)
예제 #18
0
 def test_naive_until_gets_converted_to_utc(self):
     recurs = Recurrence(
         rrules=[Rule(
             recurrence.DAILY,
             until=datetime(2014, 1, 1, 0, 0, 0))
         ],
     )
     value = recurrence.serialize(recurs)
     field = RecurrenceField()
     cleaned_value = field.clean(value)
     assert cleaned_value.rrules[0].until == datetime(2014, 1, 1, 0, 0, 0, tzinfo=pytz.utc)
예제 #19
0
def test_check_max_rrules():
    rule = Rule(recurrence.WEEKLY)

    limits = Recurrence(rrules=[rule])

    value = recurrence.serialize(limits)

    field = RecurrenceField(max_rrules=0)
    with pytest.raises(forms.ValidationError) as e:
        field.clean(value)
    assert e.value.messages[0] == "Max rules exceeded. The limit is 0"
예제 #20
0
파일: conftest.py 프로젝트: evz/cream
def income_series(five_this_morning, biweekly):
    first_occurrence = Income.objects.create(
        budgeted=1000.0,
        budgeted_date=five_this_morning.date(),
        recurrences=recurrence.serialize(biweekly))

    updater = UpdateIncomeRelationsMixin()
    updater.object = first_occurrence

    updater.update_relations(update_series=True)

    return Income.objects.all()
예제 #21
0
def build_rrule_from_recurrences_rrule(rule):
    """
    Build rrule dictionary for vRecur class from a django_recurrences rrule.

    django_recurrences is a popular implementation for recurrences in django.
    https://pypi.org/project/django-recurrence/
    this is a shortcut to interface between recurrences and icalendar.
    """
    line = serialize(rule)
    if line.startswith('RRULE:'):
        line = line[6:]
    return build_rrule_from_text(line)
예제 #22
0
 def test_aware_until_gets_converted_to_utc(self):
     tz = pytz.timezone('America/Adak')
     until = datetime(2014, 1, 1, 0, 0, 0, tzinfo=tz)
     recurs = Recurrence(
         rrules=[Rule(
             recurrence.DAILY,
             until=until)
         ],
     )
     value = recurrence.serialize(recurs)
     field = RecurrenceField()
     cleaned_value = field.clean(value)
     assert cleaned_value.rrules[0].until == until.astimezone(pytz.utc)
예제 #23
0
파일: conftest.py 프로젝트: evz/cream
def expense_series(five_this_morning, monthly, income_series):
    expense = Expense.objects.create(
        budgeted_date=five_this_morning.date(),
        budgeted_amount=100.0,
        description='hundred bucks worth of twinkies',
        recurrences=recurrence.serialize(monthly))

    updater = UpdateExpenseRelationsMixin()
    updater.object = expense

    updater.update_relations(update_series=True)

    return Expense.objects.all()
def test_bug_in_count_and_until_rule_serialization():
    # This tests a bug in the way we serialize rules with instance
    # counts and an until date. We should really raise a
    # ValidationError in validate if you specify both, but we
    # currently don't. Once we start doing this, this test can be
    # modified to check an exception is raised.
    rule = Rule(recurrence.WEEKLY,
                count=7,
                until=datetime(2014, 10, 31, 0, 0, 0))

    serialized = recurrence.serialize(rule)

    # Note that we've got no UNTIL value here
    assert 'RRULE:FREQ=WEEKLY;COUNT=7' == serialized
예제 #25
0
파일: test_income.py 프로젝트: evz/cream
def test_budget_income(client, biweekly, five_this_morning):
    budgeted_date = five_this_morning.date()

    post_data = {
        'budgeted': 1500.0,
        'budgeted_date': budgeted_date,
        'recurrences': recurrence.serialize(biweekly)
    }

    response = client.post(reverse('create-income'), post_data)

    assert response.status_code == 302
    assert response.url == '/'
    assert Income.objects.filter(budgeted=1500).count() == 27
예제 #26
0
    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        elif isinstance(value, recurrence.Recurrence):
            value = recurrence.serialize(value)

        widget_init_js = ('<script type="text/javascript">'
                          'new recurrence.widget.Widget(\'%s\', %s);'
                          '</script>') % (attrs['id'],
                                          json.dumps(self.js_widget_options))

        return safestring.mark_safe(u'%s\n%s' %
                                    (super(RecurrenceWidget, self).render(
                                        name, value, attrs), widget_init_js))
예제 #27
0
 def test_naive_until_gets_converted_to_utc(self):
     recurs = Recurrence(rrules=[
         Rule(recurrence.DAILY, until=datetime(2014, 1, 1, 0, 0, 0))
     ], )
     value = recurrence.serialize(recurs)
     field = RecurrenceField()
     cleaned_value = field.clean(value)
     assert cleaned_value.rrules[0].until == datetime(2014,
                                                      1,
                                                      1,
                                                      0,
                                                      0,
                                                      0,
                                                      tzinfo=pytz.utc)
def test_complex_rule_serialization_with_weekday_instance():
    rule = Rule(
        recurrence.WEEKLY,
        interval=17,
        wkst=recurrence.to_weekday(1),
        count=7,
        byday=[recurrence.to_weekday('-1MO'),
               recurrence.to_weekday('TU')],
        bymonth=[1, 3])

    serialized = recurrence.serialize(rule)
    assert ('RRULE:FREQ=WEEKLY;INTERVAL=17;WKST=TU;'
            'COUNT=7;BYDAY=-1MO,TU;BYMONTH=1,3') == serialized
    assert recurrence.deserialize(serialized) == Recurrence(rrules=[rule])
def test_check_max_rrules():
    rule = Rule(
        recurrence.WEEKLY
    )

    limits = Recurrence(
        rrules=[rule]
    )

    value = recurrence.serialize(limits)

    field = RecurrenceField(max_rrules=0)
    with pytest.raises(forms.ValidationError) as e:
        field.clean(value)
    assert e.value.messages[0] == "Max rules exceeded. The limit is 0"
예제 #30
0
    def render(self, name, value, attrs=None):
        if value is None:
            value = ''
        elif isinstance(value, recurrence.Recurrence):
            value = recurrence.serialize(value)

        widget_init_js = (
            '<script type="text/javascript">'
            'new recurrence.widget.Widget(\'%s\', %s);'
            '</script>'
        ) % (attrs['id'], json.dumps(self.js_widget_options))

        return safestring.mark_safe(u'%s\n%s' % (
            super(RecurrenceWidget, self).render(name, value, attrs),
            widget_init_js))
예제 #31
0
def test_check_max_rdates():
    limits = Recurrence(rdates=[
        datetime(2014, 1, 1, 0, 0, 0),
        datetime(2014, 1, 2, 0, 0, 0),
    ])

    value = recurrence.serialize(limits)

    field = RecurrenceField(max_rdates=2)
    field.clean(value)

    field = RecurrenceField(max_rdates=1)
    with pytest.raises(forms.ValidationError) as e:
        field.clean(value)
    assert e.value.messages[0] == "Max dates exceeded. The limit is 1"
예제 #32
0
    def test_naive_rdates_converted_to_utc(self):
        limits = Recurrence(rdates=[
            datetime(2014, 1, 1, 0, 0, 0),
            datetime(2014, 1, 2, 0, 0, 0),
        ], )

        value = recurrence.serialize(limits)

        field = RecurrenceField()
        cleaned_value = field.clean(value)
        assert cleaned_value.rdates == [
            datetime(2014, 1, 1, 0, 0, 0, tzinfo=pytz.utc),
            datetime(2014, 1, 2, 0, 0, 0, tzinfo=pytz.utc),
        ]
        for rdate in cleaned_value.rdates:
            assert rdate.tzname() == 'UTC'
def test_bug_in_count_and_until_rule_serialization():
    # This tests a bug in the way we serialize rules with instance
    # counts and an until date. We should really raise a
    # ValidationError in validate if you specify both, but we
    # currently don't. Once we start doing this, this test can be
    # modified to check an exception is raised.
    rule = Rule(
        recurrence.WEEKLY,
        count=7,
        until=datetime(2014, 10, 31, 0, 0, 0)
    )

    serialized = recurrence.serialize(rule)

    # Note that we've got no UNTIL value here
    assert 'RRULE:FREQ=WEEKLY;COUNT=7' == serialized
def test_complex_rule_serialization_with_weekday_instance():
    rule = Rule(
        recurrence.WEEKLY,
        interval=17,
        wkst=recurrence.to_weekday(1),
        count=7,
        byday=[
            recurrence.to_weekday('-1MO'),
            recurrence.to_weekday('TU')
        ],
        bymonth=[1, 3]
    )

    serialized = recurrence.serialize(rule)
    assert ('RRULE:FREQ=WEEKLY;INTERVAL=17;WKST=TU;'
            'COUNT=7;BYDAY=-1MO,TU;BYMONTH=1,3') == serialized
    assert recurrence.deserialize(serialized) == Recurrence(rrules=[rule])
예제 #35
0
    def test_dt_start_and_dtend_converts_to_utc(self):
        """Convert the values for dtstart and dtend to UTC."""
        tz = pytz.timezone('America/Adak')

        limits = Recurrence(
            dtstart=datetime(2014, 1, 1, 0, 0, 0, tzinfo=tz),
            dtend=datetime(2014, 2, 3, 0, 0, 0, tzinfo=tz),
        )

        value = recurrence.serialize(limits)

        field = RecurrenceField(required=False)
        cleaned_value = field.clean(value)
        assert cleaned_value.dtstart == datetime(2014, 1, 1, 0, 0, 0, tzinfo=tz).astimezone(pytz.utc)
        assert cleaned_value.dtend == datetime(2014, 2, 3, 0, 0, 0, tzinfo=tz).astimezone(pytz.utc)
        assert cleaned_value.dtstart.tzname() == 'UTC'
        assert cleaned_value.dtend.tzname() == 'UTC'
예제 #36
0
    def test_aware_rdates_converted_to_utc(self):
        tz = pytz.timezone('America/Adak')
        limits = Recurrence(rdates=[
            datetime(2014, 1, 1, 0, 0, 0, tzinfo=tz),
            datetime(2014, 1, 2, 0, 0, 0, tzinfo=tz),
        ], )

        value = recurrence.serialize(limits)

        field = RecurrenceField()
        cleaned_value = field.clean(value)
        assert cleaned_value.rdates == [
            datetime(2014, 1, 1, 0, 0, 0, tzinfo=tz).astimezone(pytz.utc),
            datetime(2014, 1, 2, 0, 0, 0, tzinfo=tz).astimezone(pytz.utc),
        ]
        for rdate in cleaned_value.rdates:
            assert rdate.tzname() == 'UTC'
def test_check_max_rdates():
    limits = Recurrence(
        rdates=[
            datetime(2014, 1, 1, 0, 0, 0),
            datetime(2014, 1, 2, 0, 0, 0),
        ]
    )

    value = recurrence.serialize(limits)

    field = RecurrenceField(max_rdates=2)
    field.clean(value)

    field = RecurrenceField(max_rdates=1)
    with pytest.raises(forms.ValidationError) as e:
        field.clean(value)
    assert e.value.messages[0] == "Max dates exceeded. The limit is 1"
예제 #38
0
    def test_naive_rdates_converted_to_utc(self):
        limits = Recurrence(
            rdates=[
                datetime(2014, 1, 1, 0, 0, 0),
                datetime(2014, 1, 2, 0, 0, 0),
            ],
        )

        value = recurrence.serialize(limits)

        field = RecurrenceField()
        cleaned_value = field.clean(value)
        assert cleaned_value.rdates == [
            datetime(2014, 1, 1, 0, 0, 0, tzinfo=pytz.utc),
            datetime(2014, 1, 2, 0, 0, 0, tzinfo=pytz.utc),
        ]
        for rdate in cleaned_value.rdates:
            assert rdate.tzname() == 'UTC'
    def test_should_create_campaign(self):
        r_rule = recurrence.Rule(recurrence.DAILY)

        obj = {
            "name": "My super awesome campaign",
            "description": "Super-cool campaign",
            "start": timezone.now(),
            "rule": serialize(r_rule)
        }

        self.client.force_login(user=self.user1)
        r = self.client.post('/api/campaigns/', data=obj)

        t = r.json()
        assert t['name'] == obj['name']

        o = Campaign.objects.get(pk=t['id'])
        assert o.owner == self.user1
예제 #40
0
파일: test_income.py 프로젝트: evz/cream
def test_budget_income_different_start(client, biweekly, five_this_morning):
    # Make sure the start date is not today
    budgeted_date = (five_this_morning - timedelta(days=1)).date()
    start_date = five_this_morning.date()

    post_data = {
        'budgeted': 1500.0,
        'budgeted_date': budgeted_date,
        'recurrences': recurrence.serialize(biweekly)
    }

    response = client.post(reverse('create-income'), post_data)

    assert response.status_code == 302
    assert response.url == '/'

    incomes = Income.objects.order_by('budgeted_date')
    assert incomes.first().budgeted_date == start_date
    assert incomes.count() == 27
예제 #41
0
    def test_aware_rdates_converted_to_utc(self):
        tz = pytz.timezone('America/Adak')
        limits = Recurrence(
            rdates=[
                datetime(2014, 1, 1, 0, 0, 0, tzinfo=tz),
                datetime(2014, 1, 2, 0, 0, 0, tzinfo=tz),
            ],
        )

        value = recurrence.serialize(limits)

        field = RecurrenceField()
        cleaned_value = field.clean(value)
        assert cleaned_value.rdates == [
            datetime(2014, 1, 1, 0, 0, 0, tzinfo=tz).astimezone(pytz.utc),
            datetime(2014, 1, 2, 0, 0, 0, tzinfo=tz).astimezone(pytz.utc),
        ]
        for rdate in cleaned_value.rdates:
            assert rdate.tzname() == 'UTC'
예제 #42
0
파일: test_expense.py 프로젝트: evz/cream
def test_update_partial_series(client, expense_series):
    somewhere_in_the_middle = expense_series[6]

    response = client.get(
        reverse('update-expense', args=(somewhere_in_the_middle.id, )))

    assert response.status_code == 200

    budgeted_dt = datetime.combine(somewhere_in_the_middle.budgeted_date,
                                   datetime.min.time())
    a_day_later = budgeted_dt + timedelta(days=1)
    end_date = a_day_later + timedelta(days=365)

    rule = recurrence.Rule(recurrence.WEEKLY,
                           interval=1,
                           byday=a_day_later.weekday(),
                           until=end_date)

    new_recurrence = recurrence.Recurrence(dtstart=a_day_later,
                                           include_dtstart=False,
                                           rrules=[rule])

    post_data = {
        'budgeted_amount': 150.0,
        'budgeted_date': a_day_later.date(),
        'description': 'hundred bucks worth of twinkies',
        'recurrences': recurrence.serialize(new_recurrence),
        'income': somewhere_in_the_middle.income.id,
        'first_occurrence': somewhere_in_the_middle.first_occurrence.id,
        'update_all': 'Yes',
    }

    response = client.post(
        reverse('update-expense', args=(somewhere_in_the_middle.id, )),
        post_data)

    assert response.status_code == 302
    assert response.url == reverse(
        'income-detail', args=(somewhere_in_the_middle.income.slug, ))

    assert Expense.objects.filter(budgeted_amount=100).count() == 6
    assert Expense.objects.filter(budgeted_amount=150).count() == 53
예제 #43
0
def test_strip_dtstart_and_dtend_if_required():
    rule = Rule(recurrence.WEEKLY)

    limits = Recurrence(dtstart=datetime(2014, 1, 1, 0, 0, 0),
                        dtend=datetime(2014, 2, 3, 0, 0, 0),
                        rrules=[rule])

    value = recurrence.serialize(limits)

    field = RecurrenceField()
    cleaned_value = field.clean(value)
    assert cleaned_value == limits
    assert cleaned_value.dtstart == datetime(2014, 1, 1, 0, 0, 0)
    assert cleaned_value.dtend == datetime(2014, 2, 3, 0, 0, 0)

    field = RecurrenceField(accept_dtstart=False, accept_dtend=False)
    cleaned_value = field.clean(value)
    assert cleaned_value != limits
    assert cleaned_value.dtstart is None
    assert cleaned_value.dtend is None
def test_strip_dtstart_and_dtend_if_required():
    rule = Rule(
        recurrence.WEEKLY
    )

    limits = Recurrence(
        dtstart=datetime(2014, 1, 1, 0, 0, 0),
        dtend=datetime(2014, 2, 3, 0, 0, 0),
        rrules=[rule]
    )

    value = recurrence.serialize(limits)

    field = RecurrenceField()
    cleaned_value = field.clean(value)
    assert cleaned_value == limits
    assert cleaned_value.dtstart == datetime(2014, 1, 1, 0, 0, 0)
    assert cleaned_value.dtend == datetime(2014, 2, 3, 0, 0, 0)

    field = RecurrenceField(accept_dtstart=False, accept_dtend=False)
    cleaned_value = field.clean(value)
    assert cleaned_value != limits
    assert cleaned_value.dtstart is None
    assert cleaned_value.dtend is None
예제 #45
0
 def get_db_prep_value(self, value, connection=None, prepared=False):
     if isinstance(value, basestring):
         value = recurrence.deserialize(value)
     return recurrence.serialize(value)
예제 #46
0
 def get_rule(self):
     if self.recurrence.rrules is not None:
         if len(self.recurrence.rrules) > 0:
             return serialize(self.recurrence.rrules[0])
     return None
예제 #47
0
 def get_prep_value(self, value):
     if not isinstance(value, string_types):
         value = recurrence.serialize(value)
     return value
예제 #48
0
 def get_prep_value(self, value):
     print('getprepval', value)
     if not isinstance(value, string_types):
         value = recurrence.serialize(value)
     return value
예제 #49
0
 def get_prep_value(self, value):
     if isinstance(value, basestring):
         value = recurrence.deserialize(value)
     return recurrence.serialize(value)