Esempio n. 1
0
def test_event_list_page(admin_webtest_client, models, factories):
    event = factories.EventFactory()

    url = reverse('admin:event-detail', kwargs={'pk': event.pk})

    response = admin_webtest_client.get(url)
    assert response.status_code == 200

    new_open_at = to_current_timezone(
        event.registration_open_at.replace(microsecond=0) + timezone.timedelta(10)
    )
    new_close_at = to_current_timezone(
        event.registration_close_at.replace(microsecond=0) + timezone.timedelta(20)
    )

    response.forms[1]['name'] = 'New Test Event Name'
    response.forms[1]['registration_open_at'] = new_open_at.strftime('%Y-%m-%d %H:%M:%S')
    response.forms[1]['registration_close_at'] = new_close_at.strftime('%Y-%m-%d %H:%M:%S')

    form_response = response.forms[1].submit()
    assert form_response.status_code == 302

    updated_event = models.Event.objects.get(name='New Test Event Name')
    assert to_current_timezone(updated_event.registration_open_at) == new_open_at
    assert to_current_timezone(updated_event.registration_close_at) == new_close_at
Esempio n. 2
0
def time_range_generator(start, end, html=False):
    """ 
    Generate time range strings from a given start and end date/time. 
    
    If html is True, a string of the format

        "Dec. 28, 2017, 3:30 a.m. – Dec. 28, 2017, 3:30 a.m."

    will be returned. Otherwise, we will return a string of the format

        "12/28/2017 03:30 AM - 12/28/2017 03:30 AM"

    """

    # The seperator to use between start and end date/times
    separator = " – " if html else " - "

    # The function to use to format a datetime object into a string
    datetime_fmtr_func = format if html else localize_input

    # The string format to be used by the date/time formatter function
    fmt_str = settings.DATETIME_FORMAT if html else DATETIME_INPUT_FORMAT

    return separator.join([
        datetime_fmtr_func(to_current_timezone(start), fmt_str),
        datetime_fmtr_func(to_current_timezone(end), fmt_str),
    ])
    def test_clean_bad_time_range_shorter(self):
        """ Test an improperly formatted time range (single date)"""
        time_range_str = localize_input(to_current_timezone(self.today),
                                        DATETIME_INPUT_FORMAT)

        with self.assertRaises(ValidationError):
            self.field.clean(time_range_str)
Esempio n. 4
0
 def format_value(self, value):
     try:
         value = to_current_timezone(value)
     except Exception:
         pass
     val = super().format_value(value)
     return val
Esempio n. 5
0
def switch_user(request, new_user):
    '''Switch to another user and remember currently logged in user in the
       session. Reserved to superusers.'''
    logger = logging.getLogger(__name__)
    if constants.SWITCH_USER_SESSION_KEY in request.session:
        messages.error(request, _('Your user is already switched, go to your '
                                  'account page and come back to your original '
                                  'user to do it again.'))
    else:
        if not request.user.is_superuser:
            raise PermissionDenied
        switched = {}
        for key in (SESSION_KEY, BACKEND_SESSION_KEY, HASH_SESSION_KEY,
                    constants.LAST_LOGIN_SESSION_KEY):
            switched[key] = request.session[key]
        user = authenticate(user=new_user)
        login(request, user, 'switch')
        request.session[constants.SWITCH_USER_SESSION_KEY] = switched
        if constants.LAST_LOGIN_SESSION_KEY not in request.session:
            request.session[constants.LAST_LOGIN_SESSION_KEY] = \
                localize(to_current_timezone(new_user.last_login), True)
        messages.info(request, _('Successfully switched to user %s') %
                      new_user.get_full_name())
        logger.info(u'switched to user %s', new_user)
        return continue_to_next_url(request)
Esempio n. 6
0
 def decompress(self, value):
     if isinstance(value, str):
         return value.split(" ", 1)
     elif isinstance(value, datetime):
         value = to_current_timezone(value)
         return [value.date(), value.time().replace(microsecond=0)]
     return [None, None]
Esempio n. 7
0
def switch_user(request, new_user):
    '''Switch to another user and remember currently logged in user in the
       session. Reserved to superusers.'''
    logger = logging.getLogger(__name__)
    if constants.SWITCH_USER_SESSION_KEY in request.session:
        messages.error(request, _('Your user is already switched, go to your '
                                  'account page and come back to your original '
                                  'user to do it again.'))
    else:
        if not request.user.is_superuser:
            raise PermissionDenied
        switched = {}
        for key in (SESSION_KEY, BACKEND_SESSION_KEY, HASH_SESSION_KEY,
                    constants.LAST_LOGIN_SESSION_KEY):
            switched[key] = request.session[key]
        user = authenticate(user=new_user)
        auth_login(request, user)
        request.session[constants.SWITCH_USER_SESSION_KEY] = switched
        if constants.LAST_LOGIN_SESSION_KEY not in request.session:
            request.session[constants.LAST_LOGIN_SESSION_KEY] = \
                    localize(to_current_timezone(new_user.last_login), True)
        messages.info(request, _('Successfully switched to user %s') %
                      new_user.get_full_name())
        logger.info(u'switched to user %s', new_user)
        return continue_to_next_url(request)
Esempio n. 8
0
 def decompress(self, value):
     if value:
         value = to_current_timezone(value)
         j_date_obj = GregorianToJalali(gyear=value.year, gmonth=value.month, gday=value.day)
         date_str = '%d-%.2d-%.2d' % (j_date_obj.jyear, j_date_obj.jmonth, j_date_obj.jday)
         return [date_str, value.time().replace(microsecond=0)]
     return [None, None]
Esempio n. 9
0
 def decompress(self, value):
     if isinstance(value, str):
         return value.split(" ", 1)
     elif isinstance(value, datetime):
         value = to_current_timezone(value)
         return [value.date(), value.time().replace(microsecond=0)]
     return [None, None]
Esempio n. 10
0
 def decompress(self, value):
     if value:
         value = to_current_timezone(value)
         return [
             value.date(),
             value.time().replace(microsecond=0, second=0)
         ]
     return [None, None]
    def test_format_value_given_none_none(self):
        """ Test format_value given (None, None) for time_range """
        result = self.widget.format_value(time_range=(None, None), )

        # Split returned string by separator
        start, end, *extra = result.split(" - ")

        # There should be no items in the extra list
        self.assertFalse(extra, "Too many dates in output")
        # Start time and end time both should be the same by default
        self.assertEqual(start, end, "Start date not equivalent to end date")

        # Current hour is found by getting the current time in the current
        # timezone and rounding down to the closest hour (i.e. replacing
        # the minutes, seconds, and microseconds in the datetime object
        # with 0).
        cur_hour = to_current_timezone(self.now).replace(
            minute=0,
            second=0,
            microsecond=0,
        )
        # Round current time up to nearest hour.
        expected = cur_hour + datetime.timedelta(hours=1)

        # Parse actual start time into datetime object
        actual = datetime.datetime.strptime(start, DATETIME_INPUT_FORMAT)

        # (Case I) The actual time and expected time should almost always be
        # equal, since they are the result of rounding up to the closest hour.
        #
        # (Case II) The only exception to this rule is when the "expected" time
        # (time at the start of the test) is right on the edge of the next
        # hour, meaning the "actual" time assigned to both ends of the
        # time_range field could run over into the next hour.
        #
        # Examples:
        #
        # Case I)
        #
        #    value       yyyy-mm-dd hh-mm-ss.µµµµµµ
        # -----------   ----------------------------
        #   expected  =  2017-12-29 02:26:59.896882
        #             =  2017-12-29 03:00:00.000000
        #    actual   =  2017-12-29 02:27:59.341242
        #             =  2017-12-29 03:00:00.000000
        # Case II)
        #
        #    value       yyyy-mm-dd hh-mm-ss.µµµµµµ
        # -----------   ----------------------------
        #   expected  =  2017-12-29 02:59:59.896882
        #             =  2017-12-29 03:00:00.000000
        #    actual   =  2017-12-29 03:00:01.341242
        #             =  2017-12-29 04:00:00.000000
        #
        self.assertLessEqual(
            actual - expected, datetime.timedelta(hours=1),
            "format_value gave a current date/time outside the expected " +
            "1-hour error threshhold")
Esempio n. 12
0
 def is_due_today(self):
     """
     Check if the task due date is today
     """
     date_now = to_current_timezone(timezone.now()).date()
     if self.due_date == date_now:
         return True
     else:
         return False
    def test_clean_bad_time_range_longer(self):
        """ Test an improperly formatted time range (tuple with >2 dates) """
        time_range = [
            localize_input(to_current_timezone(self.today),
                           DATETIME_INPUT_FORMAT),
        ] * 4
        time_range_str = " - ".join(time_range)

        with self.assertRaises(ValidationError):
            self.field.clean(time_range_str)
Esempio n. 14
0
def login(request, user, how, **kwargs):
    '''Login a user model, record the authentication event and redirect to next
       URL or settings.LOGIN_REDIRECT_URL.'''
    last_login = user.last_login
    auth_login(request, user)
    if constants.LAST_LOGIN_SESSION_KEY not in request.session:
        request.session[constants.LAST_LOGIN_SESSION_KEY] = \
                localize(to_current_timezone(last_login), True)
    record_authentication_event(request, how)
    return continue_to_next_url(request, **kwargs)
Esempio n. 15
0
 def is_due(self):
     """
     Return True if this task crossed due date, otherwise false.
     """
     # Convert to current tz, otherwise we are comparing with utc. the date
     # will be entered respect to our current tz
     date_now = to_current_timezone(timezone.now()).date()
     if not self.is_complete() and self.due_date < date_now:
         return True
     else:
         return False
Esempio n. 16
0
def test_event_list_page(admin_webtest_client, models):
    url = reverse('admin:event-create')
    response = admin_webtest_client.get(url)
    assert response.status_code == 200

    open_at = to_current_timezone(
        timezone.now().replace(microsecond=0) + timezone.timedelta(10)
    )
    close_at = to_current_timezone(
        timezone.now().replace(microsecond=0) + timezone.timedelta(20)
    )

    response.form['name'] = 'Test Event'
    response.form['registration_open_at'] = open_at.strftime('%Y-%m-%d %H:%M:%S')
    response.form['registration_close_at'] = close_at.strftime('%Y-%m-%d %H:%M:%S')

    form_response = response.form.submit()
    assert form_response.status_code == 302

    created_event = models.Event.objects.get(name='Test Event')
    assert to_current_timezone(created_event.registration_open_at) == open_at
    assert to_current_timezone(created_event.registration_close_at) == close_at
Esempio n. 17
0
def login(request, user, how, service_slug=None, **kwargs):
    '''Login a user model, record the authentication event and redirect to next
       URL or settings.LOGIN_REDIRECT_URL.'''
    from . import hooks

    last_login = user.last_login
    auth_login(request, user)
    if hasattr(user, 'init_to_session'):
        user.init_to_session(request.session)
    if constants.LAST_LOGIN_SESSION_KEY not in request.session:
        request.session[constants.LAST_LOGIN_SESSION_KEY] = \
            localize(to_current_timezone(last_login), True)
    record_authentication_event(request, how)
    hooks.call_hooks('event', name='login', user=user, how=how, service=service_slug)
    return continue_to_next_url(request, **kwargs)
Esempio n. 18
0
    def format_value(self, time_range):
        if isinstance(time_range, str):
            return time_range

        if not time_range or None in time_range:
            # Current hour is found by getting the current time in the current
            # timezone and rounding down to the closest hour (i.e. replacing
            # the minutes, seconds, and microseconds in the datetime object
            # with 0).
            cur_hour = to_current_timezone(timezone.now()).replace(
                minute=0,
                second=0,
                microsecond=0,
            )

            # Default time should be right at the upcoming hour. For example,
            # all of the following current times should be rounded up to
            # 10:00 am:
            #
            #  - 9:00 am
            #  - 9:30 am
            #  - 9:59 am
            #  - 9:24 am
            default_time = cur_hour + datetime.timedelta(hours=1)

            start_time = default_time
            end_time = default_time
        else:
            start_time, end_time, *extra = [
                to_current_timezone(t) for t in time_range
            ]

            if extra:
                raise ValueError(_("Expected exactly two dates."))

        return time_range_generator(start_time, end_time)
Esempio n. 19
0
 def test_transfer(self):
     u, a, t = DummyData.create_chain()
     a2 = DummyData.create_account(u)
     request = self.factory.post(reverse('ledger:transfer'), {
         'from_account': a.id,
         'to_account': a2.id,
         'date': to_current_timezone(now()),
         'amount': DummyData.VALUE,
     })
     request.user = u
     response = transfer(request)
     self.assertEqual(response.status_code, 302)
     a.refresh_from_db()
     a2.refresh_from_db()
     self.assertEqual(a.balance, Decimal('0.00'))
     self.assertEqual(a2.balance, DummyData.VALUE)
Esempio n. 20
0
 def test_transfer(self):
     u, a, t = DummyData.create_chain()
     a2 = DummyData.create_account(u)
     request = self.factory.post(
         reverse('ledger:transfer'), {
             'from_account': a.id,
             'to_account': a2.id,
             'date': to_current_timezone(now()),
             'amount': DummyData.VALUE,
         })
     request.user = u
     response = transfer(request)
     self.assertEqual(response.status_code, 302)
     a.refresh_from_db()
     a2.refresh_from_db()
     self.assertEqual(a.balance, Decimal('0.00'))
     self.assertEqual(a2.balance, DummyData.VALUE)
Esempio n. 21
0
 def apply(datetime_obj):
     if datetime_obj:
         return to_current_timezone(datetime_obj)
     else:
         return None
Esempio n. 22
0
 def decompress(self, value):
     if value:
         value = to_current_timezone(value)
         return [value.date(), value.time()]
     return [None, None]
Esempio n. 23
0
 def format_value(self, value):
     value = to_current_timezone(value)
     val = super().format_value(value)
     return val
Esempio n. 24
0
def datetime2jalali(g_date):
    if g_date is None:
        return None

    g_date = to_current_timezone(g_date)
    return jdatetime.datetime.fromgregorian(datetime=g_date)
Esempio n. 25
0
 def prepare_value(self, value):
     if isinstance(value, datetime):
         value = to_current_timezone(value).time()
     return super(TzAwareTimeField, self).prepare_value(value)
Esempio n. 26
0
 def prepare_value(self, value):
     value = super(DateTimeField, self).prepare_value(value)
     if isinstance(value, datetime.datetime):
         value = to_current_timezone(value)
     return value
Esempio n. 27
0
 def prepare_value(self, value):
     if isinstance(value, datetime.datetime):
         value = to_current_timezone(value)
     return value
Esempio n. 28
0
 def decompress(self, value):
     if value:
         value = to_current_timezone(value)
         return [value.date(), value.time()]
     return [None, None]
Esempio n. 29
0
 def decompress(self, value):
     if value:
         value = to_current_timezone(value)
         return [value.date(), value.time().replace(microsecond=0)]
     return [None, None]
Esempio n. 30
0
"""
Esempio n. 31
0
 def prepare_value(self, value):
     if isinstance(value, datetime.datetime):
         value = to_current_timezone(value)
     return value
Esempio n. 32
0
"""