Exemplo n.º 1
0
    def test__track_event_with_new_uuid(self, update_counters, log_data):
        uuid = 'K\xee\xab\xae\xa0\xb2\x11\xe4\xb6\x10\x8c\x89\xa5d\x0fG'
        created_at = datetime(2000, 2, 23, 4, 15)
        factories.UniqueUserFactory(uuid=uuid, created_at=created_at)
        query = {
            'e_c': constants.Events.CLICK.value,
            'e_a': constants.SOCIAL_SERVICE_FACEBOOK,
            'e_u': '3zYLCqCyEeS2EIyJpWQPRw',
            'e_t': constants.Tools.SHARING_BUTTONS.value
        }

        self.cleaned_data.update({
            'tool': constants.Tools.SHARING_BUTTONS.value,
            'source': constants.SOCIAL_SERVICE_FACEBOOK
        })
        self._test_track_event(update_counters, constants.Events.CLICK.value, query)
        log_data.check()
        self.assertEqual(
            {frozenset(obj.items()) for obj in models.UniqueUser.objects.all().values()},
            {
                frozenset([
                    ('uuid', uuid),
                    ('created_at', created_at.replace(tzinfo=timezone.UTC()))
                ]),
                frozenset([
                    ('uuid', decode_uuid(query['e_u'])),
                    ('created_at', self.timestamp.replace(tzinfo=timezone.UTC()))
                ])
            }
        )
Exemplo n.º 2
0
def opening_exception_view(request, openingid, year, month, day, time):
    """ View an opening exception, or add by POSTing """
    """ This view is odd because we don't actually want the user to see a form they can edit, the exception is created by clicking a link from another page """
    exception = None
    opening = None
    form = None
    if request.method == "POST":
        # We're adding a new exception
        form = OpeningExceptionForm(request.POST)
        if form.is_valid():
            opening = ClientOpening.objects.get(
                id=form.cleaned_data['clientOpening'])
            date = timezone.make_aware(form.cleaned_data['date'],
                                       timezone.UTC())
            exception, created = ClientOpeningException.objects.get_or_create(
                clientOpening=opening, date=date)
    if opening is None:
        opening = get_object_or_404(ClientOpening, id=openingid)
    if exception is None:
        date = timezone.make_aware(
            datetime.datetime(int(year), int(month), int(day), int(time[0:2]),
                              int(time[2:4])), timezone.UTC())
        exception = get_object_or_404(ClientOpeningException,
                                      clientOpening=opening,
                                      date=date)
    if form is None:
        form = OpeningExceptionForm({
            'clientOpening': exception.clientOpening.id,
            'date': exception.date
        })
    return render(request, 'timeslots/opening/opening_exception.html', {
        'opening': opening,
        'exception': exception,
        'form': form
    })
Exemplo n.º 3
0
    def build_chart_url(self):
        uuid = self.cleaned_data['uuid']
        products = self.cleaned_data['products']
        start_date = self.cleaned_data.get('start_date', None)
        end_date = self.cleaned_data.get('end_date', None)

        params = {
            'step': self.cleaned_data['step'],
            'renderer': self.cleaned_data['renderer']
        }

        if start_date:
            params['start_date'] = datetime(start_date.year,
                                            start_date.month,
                                            start_date.day,
                                            tzinfo=timezone.UTC()).isoformat()
        if end_date:
            params['end_date'] = datetime(end_date.year,
                                          end_date.month,
                                          end_date.day,
                                          tzinfo=timezone.UTC()).isoformat()

        if len(products) == 1:
            params['product_filter'] = json.dumps({'product__pk': products[0]})
        else:
            params['product_filter'] = json.dumps(
                {'product__pk__in': products})

        url = reverse('plata_charts_chart', args=[uuid])

        return url, mark_safe(json.dumps(params))
Exemplo n.º 4
0
class TestDateTimeField(FieldValues):
    """
    Valid and invalid values for `DateTimeField`.
    """
    valid_inputs = {
        '2001-01-01 13:00':
        datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()),
        '2001-01-01T13:00':
        datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()),
        '2001-01-01T13:00Z':
        datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()),
        datetime.datetime(2001, 1, 1, 13, 00):
        datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()),
        datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()):
        datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()),
        # Django 1.4 does not support timezone string parsing.
        '2001-01-01T14:00+01:00' if (django.VERSION > (1, 4)) else '2001-01-01T13:00Z':
        datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC())
    }
    invalid_inputs = {
        'abc': [
            'Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]'
        ],
        '2001-99-99T99:00': [
            'Datetime has wrong format. Use one of these formats instead: YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z]'
        ],
        datetime.date(2001, 1, 1): ['Expected a datetime but got a date.'],
    }
    outputs = {
        datetime.datetime(2001, 1, 1, 13, 00):
        '2001-01-01T13:00:00',
        datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()):
        '2001-01-01T13:00:00Z'
    }
    field = serializers.DateTimeField(default_timezone=timezone.UTC())
Exemplo n.º 5
0
class TestCustomInputFormatDateTimeField(FieldValues):
    """
    Valid and invalid values for `DateTimeField` with a cutom input format.
    """
    valid_inputs = {
        '1:35pm, 1 Jan 2001': datetime.datetime(2001, 1, 1, 13, 35, tzinfo=timezone.UTC()),
    }
    invalid_inputs = {
        '2001-01-01T20:50': ['Datetime has wrong format. Use one of these formats instead: hh:mm[AM|PM], DD [Jan-Dec] YYYY.']
    }
    outputs = {}
    field = serializers.DateTimeField(default_timezone=timezone.UTC(), input_formats=['%I:%M%p, %d %b %Y'])
Exemplo n.º 6
0
def commitment_exception_view(request, commitmentid, year, month, day, time):
    """ View a commitment exception, or add by POSTing """
    """ This view is odd because we don't actually want the user to see a form they can edit, the exception is created by clicking a link from another page """

    commitment = get_object_or_404(VolunteerCommitment, id=commitmentid)
    if not (request.user.is_staff
            or request.user.id == commitment.volunteer.user.id):
        # only a staff member or the committed volunteer can create a commitment exception
        return HttpResponseForbidden

    exception = None
    form = None
    if request.method == "POST":
        # We're adding a new exception
        form = CommitmentExceptionForm(request.POST)
        if form.is_valid():
            commitment = VolunteerCommitment.objects.get(
                id=form.cleaned_data['commitment'])
            date = timezone.make_aware(form.cleaned_data['date'],
                                       timezone.UTC())
            exception, created = VolunteerCommitmentException.objects.get_or_create(
                volunteerCommitment=commitment, date=date)

            #also create a new one-off opening
            opening = ClientOpening.objects.create(
                client=commitment.clientOpening.client,
                type="One-Off",
                startDate=date)
            ometadata = ClientOpeningMetadata.objects.create(
                clientOpening=opening, metadata=date.strftime('%Y-%m-%d'))
    if exception is None:
        date = timezone.make_aware(
            datetime.datetime(int(year), int(month), int(day), int(time[0:2]),
                              int(time[2:4])), timezone.UTC())
        exception = get_object_or_404(VolunteerCommitmentException,
                                      volunteerCommitment=commitment,
                                      date=date)
    if form is None:
        form = CommitmentExceptionForm({
            'commitment':
            exception.volunteerCommitment.id,
            'date':
            exception.date
        })
    return render(request, 'timeslots/commitment/commitment_exception.html', {
        'commitment': commitment,
        'exception': exception,
        'form': form
    })
Exemplo n.º 7
0
    def update_price(self, data=None):
        print("================================")
        print("     " + self.name)
        if self.id not in [-1, 0]:
            Valid_Update_Time = (datetime.datetime.now(tz=timezone.UTC()) -
                                 self.price_updated) > datetime.timedelta(
                                     minutes=5)
            #print(datetime.datetime.now(tz=timezone.UTC()))
            #print(self.price_updated)
            Data_Available = data is not None
            if not (Data_Available) and Valid_Update_Time:
                data = Coin_Data_Api_Call(self.coinmarketcap_com_id)
                print("Data Fetched for " + str(self.name))
                Data_Available = 1
                if data is None:
                    Data_Available = 0

            if Data_Available:
                self.price_btc = (data['price_btc']) or 0
                self.price_usd = data['price_usd'] or 0
                self.capitalization = data['market_cap_usd'] or 0
                self.market_supply = data['available_supply'] or 0
                self.total_supply = data['total_supply'] or 0
                if data['last_updated']:
                    self.price_updated = datetime.datetime.fromtimestamp(
                        float(data['last_updated']),
                        tz=timezone.get_current_timezone(
                        ))  # timezone.get_current_timezone()
        elif self.id in [-1]:
            Day_Today = datetime.datetime.today().weekday()
            Valid_Day = Day_Today not in [5, 6]
            Valid_Update_Time = (datetime.datetime.now(tz=timezone.UTC()) -
                                 self.price_updated) > datetime.timedelta(
                                     hours=24)

            if Valid_Update_Time and Valid_Day:
                price, date = Get_USD_Euro_Rate()
                self.price_usd = price
                self.price_updated = date
                print("Data Fetched for " + str(self.name))

        elif self.id in [0]:
            pass
            #print("Hi I am US Dollar.")
        else:
            pass

        self.last_update_try = timezone.now()
        self.save()
Exemplo n.º 8
0
def commitment_instance_view(request, clientid, year, month, day, time):
    """ Show a single commitment instance (i.e., a single date) """
    client = get_object_or_404(Client, user__id=clientid)
    commitment = None
    commitments = client.get_commitments()
    instance_date = timezone.make_aware(
        datetime.datetime(int(year), int(month), int(day), int(time[0:2]),
                          int(time[2:4])), timezone.UTC())
    is_my_commitment = False
    for c in commitments:
        instance = c.get_instance(instance_date)
        if instance:
            commitment = c
            is_my_commitment = True if commitment.volunteer.user == request.user else False
            break
    if commitment:
        exception_form = CommitmentExceptionForm({
            'commitment': commitment.id,
            'date': instance_date
        })

    return render(
        request, 'timeslots/commitment/commitment_instance_view.html', {
            "instance_date": instance_date,
            "commitment": commitment,
            "client": client,
            "instance": instance,
            "is_my_commitment": is_my_commitment,
            "exception_form": exception_form
        })
Exemplo n.º 9
0
def opening_instance_view(request, clientid, year, month, day, time):
    """ Show a single opening instance """
    volunteer = get_volunteer(request)
    client = get_object_or_404(Client, user__id=clientid)
    opening = None
    openings = client.openings.all()
    instance_date = timezone.make_aware(
        datetime.datetime(int(year), int(month), int(day), int(time[0:2]),
                          int(time[2:4])), timezone.UTC())
    for o in openings:
        instance = o.get_instance(instance_date)
        if instance:
            opening = o
            break

    if opening:
        exception_form = OpeningExceptionForm({
            'clientOpening': opening.id,
            'date': instance_date
        })
    return render(
        request, 'timeslots/opening/opening_instance_view.html', {
            "instance_date": instance_date,
            "opening": opening,
            "client": client,
            "instance": instance,
            "exception_form": exception_form
        })
Exemplo n.º 10
0
Arquivo: ajax.py Projeto: coblan/first
def get_msg(room, time_str, user_name, user_id, user_names):
    utc = timezone.UTC()
    crt = timezone.get_current_timezone()
    utc_last = None
    if time_str:
        last = timezone.datetime.strptime(time_str, '%Y-%m-%d %H:%M:%S %f')
        last = last.replace(tzinfo=crt)
        utc_last = last.astimezone(utc)

    redis_conn.set('room__%s.user_id.%s' % (room, user_id), user_name, ex=60)
    redis_conn.sadd('room__%s.user_list' % room, user_id)

    dc = has_new_msg(room, utc_last, user_names)
    if not dc:
        dc = {}
    if 'chats' not in dc:
        dc['chats'] = []
    else:
        for item in dc.get('chats'):
            item['time'] = timezone.localtime(
                item['time']).strftime('%Y-%m-%d %H:%M:%S %f')
    if 'user_names' not in dc:
        dc['user_names'] = get_user_names(room)
    dc['status'] = 'success'
    return dc
Exemplo n.º 11
0
    def test_serializer_json_with_an_event(self):
        """
        Create a ``CalendarEvent`` and test if serialize function returns the
        correct json.

        The :class:`~django_bootstrap_calendar.models.CalendarEvent` is
        created with 5 hours duration.
        """
        timestamp = datetime_safe.datetime(2014,
                                           03,
                                           16,
                                           12,
                                           30,
                                           tzinfo=timezone.UTC())
        event = CalendarEvent.objects.create(title="Some Event Test",
                                             start=timestamp,
                                             end=timestamp +
                                             timedelta(seconds=60 * 60 * 5),
                                             url='http://example.com',
                                             css_class='event-info')
        event_queryset = CalendarEvent.objects.filter(id=event.id)
        expected_json = '''{
            "result": [
                {
                    "end": "1394991000000",
                    "title": "Some Event Test",
                    "url": "http://example.com",
                    "id": 1,
                    "start": "1394973000000",
                    "class": "event-info"
                }
            ],
            "success": 1
        }'''
        self.assertJSONEqual(event_serializer(event_queryset), expected_json)
Exemplo n.º 12
0
 def expired_time(self):
     message = self.message
     now = timezone.now()
     if timezone.is_naive(self.message.expire_at):
         message.expire_at = timezone.make_aware(message.expire_at,
                                                 timezone.UTC())
     if timezone.is_naive(self.message.start_on):
         message.start_on = timezone.make_aware(message.start_on,
                                                timezone.UTC())
     date_expired = (message.expire_at - message.start_on) + \
                    message.start_on
     if now > date_expired:
         self.mark_expired()
         return True
     else:
         return False
Exemplo n.º 13
0
    def test_raw_value(self):
        inst = models.TestModel()
        inst.enc_char_field = 'This is a test string!'
        inst.enc_text_field = 'This is a test string2!'
        inst.enc_date_field = datetime.date(2011, 1, 1)
        inst.enc_datetime_field = datetime.datetime(2012,
                                                    2,
                                                    1,
                                                    1,
                                                    tzinfo=timezone.UTC())
        inst.enc_boolean_field = True
        inst.enc_null_boolean_field = True
        inst.enc_integer_field = 123456789
        inst.enc_positive_integer_field = 123456789
        inst.enc_small_integer_field = 123456789
        inst.enc_positive_small_integer_field = 123456789
        inst.enc_big_integer_field = 9223372036854775807
        inst.save()

        d = models.TestModel.objects.values()[0]
        for key, value in d.items():
            if key == 'id':
                continue
            self.assertEqual(value[:7], 'gAAAAAB',
                             '{} failed: {}'.format(key, value))

        inst.enc_null_boolean_field = None
        inst.save()

        d = models.TestModel.objects.values()[0]
        self.assertEqual(d['enc_null_boolean_field'], None)
Exemplo n.º 14
0
 def _message_queryset(self, exclude_unread=True):
     qs = Message.objects.filter(user=get_user(self.request)).filter(
         Q(expires=None)
         | Q(expires__gt=datetime.datetime.now(timezone.UTC())))
     if exclude_unread:
         qs = qs.exclude(read=True)
     return qs
Exemplo n.º 15
0
def iso_8601_to_datetime(iso):
    """Parse an iso 8601 string into a timezone aware datetime, ignoring and fractional seconds."""
    if not iso:
        return None
    dt = datetime.datetime.strptime(iso[:19], '%Y-%m-%dT%H:%M:%S')
    # strptime doesn't seem to handle timezones, parse them here
    if len(iso) == 19:
        return timezone.make_aware(dt, timezone.get_current_timezone())
    else:
        # Make the datetime UTC if Z is the timezone, ignoring fractional seconds in between
        if (len(iso) == 20 or iso[19] == '.') and iso[-1] == 'Z':
            return timezone.make_aware(dt, timezone.UTC())
        # Parse a complete timezone e.g. +00:00, checking for the correct length or ignored fractional seconds
        if (len(iso) == 25 or iso[19]
                == '.') and iso[-6] in ('+', '-') and iso[-3] == ':':
            try:
                hours = int(iso[-5:-3])
                minutes = int(iso[-2:])
                minutes += hours * 60
                if iso[-6] == '-':
                    minutes = -minutes
                return timezone.make_aware(
                    dt, timezone.get_fixed_timezone(minutes))
            except:
                # drop through and raise the exception
                pass
        raise ValueError('Invalid timezone %s.' % iso[19:])
Exemplo n.º 16
0
 def cron_to_datetime(cron):
     now = timezone.now().astimezone(tz=timezone.UTC())
     cron_year = now.year
     cron_month = now.monty if cron.month_of_year == '*' else int(
         cron.month_of_year)
     cron_day = now.monty if cron.day_of_month == '*' else int(
         cron.day_of_month)
     cron_minute = now.monty if cron.minute == '*' else int(cron.minute)
     cron_hour = now.monty if cron.hour == '*' else int(cron.hour)
     cron_task_time = datetime.datetime(cron_year,
                                        cron_month,
                                        cron_day,
                                        cron_hour,
                                        cron_minute,
                                        second=0,
                                        tzinfo=timezone.UTC())
     return cron_task_time
Exemplo n.º 17
0
def paypaltime2datetime(s):
    """Convert a PayPal time string to a DateTime."""
    naive = datetime.datetime.strptime(s, PayPalNVP.TIMESTAMP_FORMAT)
    if not settings.USE_TZ:
        return naive
    else:
        # TIMESTAMP_FORMAT is UTC
        return timezone.make_aware(naive, timezone.UTC())
Exemplo n.º 18
0
    def compress(self, data_list):
        if data_list:
            from django.utils import timezone
            tz = timezone.get_current_timezone()
            start_date, stop_date = data_list

            if start_date:
                if not start_date.tzinfo:
                    start_date = start_date.replace(tzinfo=timezone.UTC())
                start_date = start_date.astimezone(tz).replace(microsecond=0)
            if stop_date:
                if not stop_date.tzinfo:
                    stop_date = stop_date.replace(tzinfo=timezone.UTC())
                stop_date = stop_date.astimezone(tz).replace(
                    microsecond=999999)
            return slice(start_date, stop_date)
        return None
Exemplo n.º 19
0
    def test_make_aware_pytz_non_existent(self):
        # 2:30 never happened due to DST
        non_existent = datetime.datetime(2015, 3, 29, 2, 30)

        with self.assertRaises(pytz.NonExistentTimeError):
            timezone.make_aware(non_existent, timezone=CET)

        std = timezone.make_aware(non_existent, timezone=CET, is_dst=False)
        dst = timezone.make_aware(non_existent, timezone=CET, is_dst=True)
        self.assertEqual(std - dst, datetime.timedelta(hours=1))
        self.assertEqual(std.tzinfo.utcoffset(std), datetime.timedelta(hours=1))
        self.assertEqual(dst.tzinfo.utcoffset(dst), datetime.timedelta(hours=2))

        # round trip to UTC then back to CET
        std = timezone.localtime(timezone.localtime(std, timezone.UTC()), CET)
        dst = timezone.localtime(timezone.localtime(dst, timezone.UTC()), CET)
        self.assertEqual((std.hour, std.minute), (3, 30))
        self.assertEqual((dst.hour, dst.minute), (1, 30))
Exemplo n.º 20
0
 def enforce_timezone(self, value):
     """
     When `self.default_timezone` is `None`, always return naive datetimes.
     When `self.default_timezone` is not `None`, always return aware datetimes.
     """
     if (self.default_timezone is not None) and not timezone.is_aware(value):
         return timezone.make_aware(value, self.default_timezone)
     elif (self.default_timezone is None) and timezone.is_aware(value):
         return timezone.make_naive(value, timezone.UTC())
     return value
Exemplo n.º 21
0
 def end_date_iso(self):
     """
     Return a offset-aware date in iso format
     """
     if self.end_date:
         return datetime(self.end_date.year,
                         self.end_date.month,
                         self.end_date.day,
                         tzinfo=timezone.UTC()).isoformat()
     return ""
Exemplo n.º 22
0
 def test_valid_webaccept(self):
     paypal_input = b'payment_type=instant&payment_date=23%3A04%3A06%20Feb%2002%2C%202009%20PDT&payment_status=Completed&address_status=confirmed&payer_status=verified&first_name=John&last_name=Smith&payer_email=buyer%40paypalsandbox.com&payer_id=TESTBUYERID01&address_name=John%20Smith&address_country=United%20States&address_country_code=US&address_zip=95131&address_state=CA&address_city=San%20Jose&address_street=123%20any%20street&business=seller%40paypalsandbox.com&receiver_email=seller%40paypalsandbox.com&receiver_id=seller%40paypalsandbox.com&residence_country=US&item_name=something&item_number=AK-1234&quantity=1&shipping=3.04&tax=2.02&mc_currency=USD&mc_fee=0.44&mc_gross=12.34&mc_gross1=12.34&txn_type=web_accept&txn_id=593976436&notify_version=2.1&custom=xyz123&invoice=abc1234&test_ipn=1&verify_sign=AFcWxV21C7fd0v3bYYYRCpSSRl31Awsh54ABFpebxm5s9x58YIW-AWIb'
     response = self.post_to_ipn_handler(paypal_input)
     self.assertEqual(response.status_code, 200)
     ipn = self.get_ipn()
     self.assertFalse(ipn.flag)
     self.assertEqual(ipn.mc_gross, Decimal("12.34"))
     # For tests, we get conversion to UTC because this is all SQLite supports.
     self.assertEqual(ipn.payment_date,
                      datetime(2009, 2, 3, 7, 4, 6, tzinfo=timezone.UTC()))
Exemplo n.º 23
0
class TestNaiveDateTimeField(FieldValues):
    """
    Valid and invalid values for `DateTimeField` with naive datetimes.
    """
    valid_inputs = {
        datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()): datetime.datetime(2001, 1, 1, 13, 00),
        '2001-01-01 13:00': datetime.datetime(2001, 1, 1, 13, 00),
    }
    invalid_inputs = {}
    outputs = {}
    field = serializers.DateTimeField(default_timezone=None)
Exemplo n.º 24
0
def naive_datetime(value):
    if not settings or not timezone:
        return value

    if getattr(settings, "USE_TZ", False):
        default_tz = timezone.get_default_timezone()

        if isinstance(value, datetime.datetime) and timezone.is_aware(value):
            return timezone.make_naive(value, default_tz)
        elif isinstance(value, datetime.date):
            value = timezone.make_naive(
                datetime.datetime(value.year, value.month, value.day, tzinfo=timezone.UTC()),
                default_tz)

            return value.date()
        elif isinstance(value, datetime.time):
            value = timezone.make_naive(datetime.datetime(
                2001, 1, 1, hour=value.hour, minute=value.minute, second=value.second,
                microsecond=value.microsecond, tzinfo=timezone.UTC()), default_tz)

            return value.time()

    return value
Exemplo n.º 25
0
class TestDateTimeRangeField(TestCase, FieldValues):
    """
    Values for `ListField` with CharField as child.
    """
    if compat.DateTimeTZRange is not None:
        valid_inputs = [
            ({'lower': '2001-01-01T13:00:00Z',
              'upper': '2001-02-02T13:00:00Z',
              'bounds': '[)'},
             compat.DateTimeTZRange(
                 **{'lower': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()),
                    'upper': datetime.datetime(2001, 2, 2, 13, 00, tzinfo=timezone.UTC()),
                    'bounds': '[)'})),
            ({'upper': '2001-02-02T13:00:00Z',
              'bounds': '[)'},
             compat.DateTimeTZRange(
                 **{'upper': datetime.datetime(2001, 2, 2, 13, 00, tzinfo=timezone.UTC()),
                    'bounds': '[)'})),
            ({'lower': '2001-01-01T13:00:00Z',
              'bounds': '[)'},
             compat.DateTimeTZRange(
                 **{'lower': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()),
                    'bounds': '[)'})),
            ({'empty': True},
             compat.DateTimeTZRange(**{'empty': True})),
            ({}, compat.DateTimeTZRange()),
        ]
        invalid_inputs = [
            ({'lower': 'a'}, ['Datetime has wrong format. Use one of these'
                              ' formats instead: '
                              'YYYY-MM-DDThh:mm[:ss[.uuuuuu]][+HH:MM|-HH:MM|Z].']),
            ('not a dict', ['Expected a dictionary of items but got type "str".']),
        ]
        outputs = [
            (compat.DateTimeTZRange(
                **{'lower': datetime.datetime(2001, 1, 1, 13, 00, tzinfo=timezone.UTC()),
                   'upper': datetime.datetime(2001, 2, 2, 13, 00, tzinfo=timezone.UTC())}),
                {'lower': '2001-01-01T13:00:00Z',
                 'upper': '2001-02-02T13:00:00Z',
                 'bounds': '[)'}),
            (compat.DateTimeTZRange(**{'empty': True}),
             {'empty': True}),
            (compat.DateTimeTZRange(),
             {'bounds': '[)', 'lower': None, 'upper': None}),
        ]
    field = DateTimeRangeField()

    def test_no_source_on_child(self):
        with pytest.raises(AssertionError) as exc_info:
            DateTimeRangeField(child=serializers.IntegerField(source='other'))

        assert str(exc_info.value) == (
            "The `source` argument is not meaningful when applied to a `child=` field. "
            "Remove `source=` from the field declaration."
        )
Exemplo n.º 26
0
    def test_csv_response(self):
        course_enrollment = self.enroll_student(self.course)
        enrolled_at = datetime(year=2015,
                               month=1,
                               day=1,
                               tzinfo=timezone.UTC())
        course_enrollment.created = enrolled_at
        course_enrollment.save()

        response = self.get_course_enrollment_stats(self.course,
                                                    response_format="csv")
        rows = self.get_csv_response_rows(response)

        self.assertEqual(200, response.status_code)
        self.assertEqual(2, len(rows))
        self.assertEqual(["2015/01/01", "1"], rows[1])
Exemplo n.º 27
0
    def strptime(self, value, format):
        value = force_str(value)

        if format == self.ISO_8601:
            parsed = parse_datetime(value)
            if parsed is None:  # Continue with other formats if doesn't match
                raise ValueError

            # Handle timezone awareness. Copied from:
            # https://github.com/tomchristie/django-rest-framework/blob/3.2.0/rest_framework/fields.py#L965-L969
            if settings.USE_TZ and not timezone.is_aware(parsed):
                return timezone.make_aware(parsed, self.default_timezone)
            elif not settings.USE_TZ and timezone.is_aware(parsed):
                return timezone.make_naive(parsed, timezone.UTC())
            return parsed
        return super(IsoDateTimeField, self).strptime(value, format)
Exemplo n.º 28
0
def _read_team_pairings(sheet, header_row, season, teams, round_, pairings, pairing_rows):
    white_col = sheet[header_row].index('WHITE')
    white_team_col = white_col - 1
    black_col = sheet[header_row].index('BLACK')
    black_team_col = black_col + 1
    result_col = sheet[header_row].index('RESULT')
    date_col = sheet[header_row].index('DATE')
    time_col = sheet[header_row].index('TIME')
    pairing_row = header_row + 1
    # Team pairings
    for j in range(len(teams) / 2):
        white_team_name = sheet[pairing_row][white_team_col]
        white_team = Team.objects.get(season=season, name__iexact=white_team_name)
        black_team_name = sheet[pairing_row][black_team_col]
        black_team = Team.objects.get(season=season, name__iexact=black_team_name)
        team_pairing = TeamPairing.objects.create(round=round_, white_team=white_team, black_team=black_team, pairing_order=j + 1)
        # Individual pairings
        for k in range(season.boards):
            white_player_name, _ = _parse_player_name(sheet[pairing_row][white_col])
            white_player, _ = Player.objects.get_or_create(lichess_username__iexact=white_player_name, defaults={'lichess_username': white_player_name})
            SeasonPlayer.objects.get_or_create(season=season, player=white_player)
            black_player_name, _ = _parse_player_name(sheet[pairing_row][black_col])
            black_player, _ = Player.objects.get_or_create(lichess_username__iexact=black_player_name, defaults={'lichess_username': black_player_name})
            SeasonPlayer.objects.get_or_create(season=season, player=black_player)
            result = sheet[pairing_row][result_col]
            if result == u'\u2694':
                result = ''
            date = sheet[pairing_row][date_col]
            time = sheet[pairing_row][time_col]
            scheduled_time = None
            if '/' in date:
                scheduled_time = datetime.strptime('%s %s' % (date, time), '%m/%d/%Y %H:%M')
                scheduled_time = scheduled_time.replace(tzinfo=timezone.UTC())
                if round_.start_date is None or scheduled_time < round_.start_date:
                    round_.start_date = scheduled_time
                    round_.save()
                game_end_estimate = scheduled_time + timedelta(hours=3)
                if round_.end_date is None or game_end_estimate > round_.end_date:
                    round_.end_date = game_end_estimate
                    round_.save()
            pairing = TeamPlayerPairing.objects.create(team_pairing=team_pairing, board_number=k + 1, white=white_player, black=black_player, result=result, scheduled_time=scheduled_time)
            pairings.append(pairing)
            pairing_rows.append(pairing_row)
            pairing_row += 1
    return result_col
Exemplo n.º 29
0
    def test__track_event_with_used_uuid(self, update_counters, log_data):
        uuid = '\xdf6\x0b\n\xa0\xb2\x11\xe4\xb6\x10\x8c\x89\xa5d\x0fG'
        created_at = datetime(2000, 2, 23, 4, 15)
        factories.UniqueUserFactory(uuid=uuid, created_at=created_at)
        query = {
            'e_c': constants.Events.CLICK.value,
            'e_a': constants.SOCIAL_SERVICE_FACEBOOK,
            'e_u': '3zYLCqCyEeS2EIyJpWQPRw',
            'e_t': constants.Tools.SHARING_BUTTONS.value
        }

        with transaction.atomic():
            tasks.track_event.delay(self.site.pk, self.timestamp, query)
        self.assertTrue(update_counters.delay.called)
        log_data.check()
        self.assertEqual(
            {frozenset(obj.items()) for obj in models.UniqueUser.objects.all().values()},
            {frozenset([
                ('uuid', uuid),
                ('created_at', created_at.replace(tzinfo=timezone.UTC()))
            ])}
        )
Exemplo n.º 30
0
 def get_context_data(self, **kwargs):
     context_data = super(DateRangeChartView,
                          self).get_context_data(**kwargs)
     self.form = context_data.get('form')
     if self.form.is_valid():
         if self.form.cleaned_data.get('start_date'):
             start_date = self.form.cleaned_data['start_date']
         else:
             start_date = timezone.now() - timedelta(days=7)
         if self.form.cleaned_data.get('end_date'):
             end_date = self.form.cleaned_data['end_date']
         else:
             end_date = timezone.now()
         self.start_date = datetime(start_date.year, start_date.month,
                                    start_date.day, 0, 0, 0)
         self.end_date = datetime(end_date.year, end_date.month,
                                  end_date.day, 23, 59)
         self.client = self.form.cleaned_data['client']
         if settings.USE_TZ:
             if pytz:
                 tz = pytz.timezone(settings.TIME_ZONE)
             else:
                 tz = timezone.UTC()
             if not timezone.is_aware(self.start_date):
                 self.start_date = tz.localize(self.start_date)
             if not timezone.is_aware(self.end_date):
                 self.end_date = tz.localize(self.end_date)
         context_data.update({
             'start_date':
             self.start_date.strftime('%m/%d/%Y'),
             'end_date':
             self.end_date.strftime('%m/%d/%Y'),
             'client_id':
             self.client.uuid,
         })
     return context_data