def test_import_event_does_not_exclude_ending_day_when_all_day_is_false(self): ical = """\ BEGIN:VCALENDAR BEGIN:VEVENT DTSTART:20130802T200000Z DTEND:20130802T203000Z DTSTAMP:20150202T092425Z UID:[email protected] SUMMARY:PythonCamp 2015 - Python Bar Camp in Cologne DESCRIPTION:Python PythonCamp 2015 - Python Bar Camp in Cologne LOCATION:GFU Cyrus AG\, Am Grauen Stein 27\, 51105 Cologne\, Germany END:VEVENT END:VCALENDAR """ importer = ICSImporter(self.calendar) importer.import_events_from_text(ical) single_day_event = Event.objects.get(uid='*****@*****.**') self.assertFalse(single_day_event.next_or_previous_time.all_day) self.assertTrue(single_day_event.next_or_previous_time.single_day) self.assertEqual( make_aware(datetime(year=2013, month=8, day=2, hour=20)), single_day_event.next_or_previous_time.dt_start ) self.assertEqual( make_aware(datetime(year=2013, month=8, day=2, hour=20, minute=30)), single_day_event.next_or_previous_time.dt_end )
def test_import_event_excludes_ending_day_when_all_day_is_true(self): ical = """\ BEGIN:VCALENDAR BEGIN:VEVENT DTSTART;VALUE=DATE:20150328 DTEND;VALUE=DATE:20150330 DTSTAMP:20150202T092425Z UID:[email protected] SUMMARY:PythonCamp 2015 - Python Bar Camp in Cologne DESCRIPTION:Python PythonCamp 2015 - Python Bar Camp in Cologne LOCATION:GFU Cyrus AG\, Am Grauen Stein 27\, 51105 Cologne\, Germany END:VEVENT END:VCALENDAR """ importer = ICSImporter(self.calendar) importer.import_events_from_text(ical) all_day_event = Event.objects.get(uid='*****@*****.**') self.assertTrue(all_day_event.next_or_previous_time.all_day) self.assertFalse(all_day_event.next_or_previous_time.single_day) self.assertEqual( make_aware(datetime(year=2015, month=3, day=28)), all_day_event.next_or_previous_time.dt_start ) self.assertEqual( make_aware(datetime(year=2015, month=3, day=29)), all_day_event.next_or_previous_time.dt_end )
def test_parse_reservations(self): jsonstr = '''{"90A05013": [ { "start": "2015-09-25 18:30", "end": "2015-09-25 19:00" }, { "start": "2015-09-25 18:30", "end": "2015-09-25 18:59" } ]} ''' expected = { "90A05013": [ { 'start': datetime(2015, 9, 25, 18, 30), 'end': datetime(2015, 9, 25, 19, 0), }, { 'start': datetime(2015, 9, 25, 18, 30), 'end': datetime(2015, 9, 25, 18, 59), }, ] } result = parse_reservations(jsonstr) self.assertEquals(expected, result)
def addEvents(): print 'Adding Events ...' c = Court.objects.count() u = User.objects.count() s = Sport.objects.count() for i in range(5000): e = Event() year = 2016 + randint(0, 50) month = randint(1, 12) day = randint(1,30) if ( month != 2 ) else randint(1, 28) hour = randint(1, 23) - 2 hour = 0 if (hour < 0) else hour minute = randint(0, 59) e.dateTime = timezone.datetime(year=year, month=month, day=day, hour=hour, minute=minute) e.endTime = timezone.datetime(year=year, month=month, day=day, hour=hour+2, minute=minute) e.court = Court.objects.all()[randint(0,c-1)] e.sport = Sport.objects.all()[randint(0,s-1)] e.creator = User.objects.all()[randint(0,u-1)] e.duration = 2 e.save() try: for i in range(randint(1,50)): e.participants.add(User.objects.get(id=randint(2,u))) except(User.DoesNotExist): pass e.save()
def get_context_data(self, **kwargs): firstweekday = 0 + SHIFT_WEEKSTART while firstweekday < 0: firstweekday += 7 while firstweekday > 6: firstweekday -= 7 month = [[]] week = 0 start = datetime(year=self.year, month=self.month, day=1, tzinfo=utc) end = datetime( year=self.year, month=self.month, day=1, tzinfo=utc ) + relativedelta(months=1) occurrences = [] cal = calendar.Calendar() cal.setfirstweekday(firstweekday) all_occurrences = self.get_queryset().filter(start_time__month=self.month, start_time__year=self.year) print '------------' print all_occurrences for day in cal.itermonthdays(self.year, self.month): current = False if day: date = datetime(year=self.year, month=self.month, day=day, tzinfo=utc) if date.date() == now().date(): current = True month[week].append((day, all_occurrences.filter(start_time__day=day), current)) if len(month[week]) == 7: month.append([]) week += 1 calendar.setfirstweekday(firstweekday) weekdays = [_(header) for header in calendar.weekheader(10).split()] ctx = {'month': month, 'date': date, 'weekdays': weekdays} return ctx
def duracao(self): if self.saida == None: return timezone.timedelta() agora = timezone.now() chegada = timezone.datetime(year=agora.year,month=agora.month,day=agora.month,hour=self.chegada.hour, minute=self.chegada.minute) saida = timezone.datetime(year=agora.year,month=agora.month,day=agora.month,hour=self.saida.hour, minute=self.saida.minute) return saida-chegada
def clean(self): super(ReportsForm, self).clean() # Invalid value, skip rest of the validation if 'period' not in self.cleaned_data: return # Handle predefined periods if self.cleaned_data['period'] == 'month': end = timezone.now().replace(day=1) - timedelta(days=1) start = end.replace(day=1) elif self.cleaned_data['period'] == 'year': year = timezone.now().year - 1 end = timezone.make_aware(timezone.datetime(year, 12, 31)) start = timezone.make_aware(timezone.datetime(year, 1, 1)) else: # Validate custom period if (not self.cleaned_data['start_date'] or not self.cleaned_data['end_date']): raise ValidationError( _('Starting and ending dates have to be specified!') ) start = self.cleaned_data['start_date'] end = self.cleaned_data['end_date'] # Sanitize timestamps self.cleaned_data['start_date'] = start.replace( hour=0, minute=0, second=0, microsecond=0 ) self.cleaned_data['end_date'] = end.replace( hour=23, minute=59, second=59, microsecond=999999 ) # Final validation if self.cleaned_data['start_date'] > self.cleaned_data['end_date']: raise ValidationError( _('Starting date has to be before ending date!') )
def test_get_previous_next_active_phase_works_with_competition_that_has_ended_but_has_phase_that_never_ends(self): self.competition.end_date = datetime(2018, 5, 25, 23, 59, tzinfo=pytz.utc) self.competition.save() self.phase_1 = CompetitionPhase.objects.create( competition=self.competition, phasenumber=1, start_date=datetime(2017, 6, 18, 23, 59), ) self.phase_2 = CompetitionPhase.objects.create( competition=self.competition, phasenumber=2, start_date=datetime(2017, 6, 30, 23, 59), phase_never_ends=True, ) self.phase_3 = CompetitionPhase.objects.create( competition=self.competition, phasenumber=3, start_date=datetime(2018, 5, 13, 23, 59), ) first_phase, previous_phase, active_phase, next_phase = get_first_previous_active_and_next_phases( self.competition) assert first_phase == self.phase_1 assert previous_phase == self.phase_3 assert active_phase == self.phase_2 assert next_phase is None
def get_context_data(self, **kwargs): ctx = self.get_category_context() month = [[]] week = 0 start = datetime(year=self.year, month=self.month, day=1, tzinfo=utc) end = datetime( year=self.year, month=self.month, day=1, tzinfo=utc ) + relativedelta(months=1) all_occurrences = LocalEvent.shows.get_occurrences( start, end, ctx.get('current_category')) for day in calendar.Calendar(firstweekday=6).itermonthdays(self.year, self.month): current = False if day: date = datetime(year=self.year, month=self.month, day=day, tzinfo=utc) occurrences = filter( lambda occ, date=date: occ.start.replace( hour=0, minute=0, second=0, microsecond=0) == date, all_occurrences) if date.date() == now().date(): current = True else: occurrences = [] month[week].append((day, occurrences, current)) if len(month[week]) == 7: month.append([]) week += 1 ctx.update({'month': month, 'date': date}) return ctx
def get_date_range_dict(): filter_by_date_default_end_date = timezone.now() date_range_dict = {'default': {'start_date': FILTER_BY_DATE_DEFAULT_START_DATE, 'end_date': filter_by_date_default_end_date}, 'week': {'start_date': timezone.now() - timezone.timedelta(days=7), 'end_date': filter_by_date_default_end_date}, 'two_weeks': {'start_date': timezone.now() - timezone.timedelta(days=14), 'end_date': filter_by_date_default_end_date}, 'month': {'start_date': timezone.now() - timezone.timedelta(days=31), 'end_date': filter_by_date_default_end_date}, 'current_month': { 'start_date': timezone.datetime(timezone.now().year, timezone.now().month, 1, tzinfo=timezone.utc), 'end_date': filter_by_date_default_end_date }, 'current_year': { 'start_date': timezone.datetime(timezone.now().year, 1, 1, tzinfo=timezone.utc), 'end_date': filter_by_date_default_end_date }, 'protective_edge': { # Dates are set based on information from Wikipedia: # he.wikipedia.org/wiki/%D7%9E%D7%91%D7%A6%D7%A2_%D7%A6%D7%95%D7%A7_%D7%90%D7%99%D7%AA%D7%9F 'start_date': timezone.datetime(2014, 7, 8, tzinfo=timezone.utc), 'end_date': timezone.datetime(2014, 8, 26, tzinfo=timezone.utc) }, } return date_range_dict
def handle(self, *args, **options): print 'Start.' start_time = timezone.datetime(2014, 9, 01, 0, 0, 0, 0, tzinfo=timezone.get_current_timezone()) end_time = timezone.datetime(2015, 8, 31, 23, 59, 0, 0, tzinfo=timezone.get_current_timezone()) range_qs = Facebook_Status.objects.filter(published__range=(start_time, end_time)) # Shkifut print 'doing shkifut' STR_SEARCH_TERMS = [u'שקיפות', ] q_objects = [Q(content__icontains=x) for x in STR_SEARCH_TERMS] joined_q_objects = q_objects[0] # | q_objects[1] | q_objects[2] self.calculate_and_save_data_for_keyword(range_qs, joined_q_objects, file_name='shkifut') # Hasadna print 'doing shkifut' STR_SEARCH_TERMS = [u'כנסת פתוחה', u'לידע ציבורי', u'מפתח התקציב', u'תקציב פתוח', u'התקציב הפתוח'] q_objects = [Q(content__icontains=x) for x in STR_SEARCH_TERMS] joined_q_objects = q_objects[0] | q_objects[1] | q_objects[2] | q_objects[3] | q_objects[4] self.calculate_and_save_data_for_keyword(range_qs, joined_q_objects, file_name='hasadna_terms') # Democracy print 'doing Democracy' STR_SEARCH_TERMS = [u'דמוקרטיה', ] q_objects = [Q(content__icontains=x) for x in STR_SEARCH_TERMS] joined_q_objects = q_objects[0] self.calculate_and_save_data_for_keyword(range_qs, joined_q_objects, file_name='democracy') # all print 'doing all' joined_q_objects = Q() self.calculate_and_save_data_for_keyword(range_qs, joined_q_objects, file_name='total') print 'Done.'
def test_assignment_with_tz(self): expected = timezone.datetime(1970, 1, 1, 0, 0, 3, tzinfo=timezone.utc) t = ForTestModel.objects.create() pre_modified = t.modified t.str_ini = '3' t.str_dt_ini = '1970-01-01 00:00:03' t.float_ini = 3.0 t.int_ini = 3 t.dt_ini = timezone.datetime(1970, 1, 1, 0, 0, 3, tzinfo=timezone.utc) t.use_numeric_field = 3.1111116 t.round_3_field = 3.1116 t.save() if hasattr(t, 'refresh_from_db'): t.refresh_from_db() else: t = ForTestModel.objects.get(id=t.id) self.assertGreater(t.modified, pre_modified) self.assertEqual(t.str_ini, expected) self.assertEqual(t.str_dt_ini, expected) self.assertEqual(t.float_ini, expected) self.assertEqual(t.int_ini, expected) self.assertEqual(t.use_numeric_field, 3.111112) self.assertEqual(t.round_3_field, 3.112)
def setUp(self): self.survey = factories.Survey.create(role=survey_models.Survey.PATIENT_FEEDBACK) self.clinic1 = factories.Clinic.create(name='Clinic1') self.clinic2 = factories.Clinic.create(name='Clinic2') self.service1 = factories.Service.create(name='Service1') self.service2 = factories.Service.create(name='Service2') dt1 = timezone.make_aware(timezone.datetime(2014, 7, 22), timezone.utc) dt2 = timezone.make_aware(timezone.datetime(2014, 7, 25), timezone.utc) visit1 = factories.Visit.create( patient=factories.Patient.create(clinic=self.clinic1), service=self.service1, visit_time=dt1) visit2 = factories.Visit.create( patient=factories.Patient.create(clinic=self.clinic2), service=self.service2, visit_time=dt2) visit3 = factories.Visit.create( patient=factories.Patient.create(clinic=self.clinic1), service=self.service2, visit_time=dt2) factories.SurveyQuestionResponse.create( visit=visit1, question__survey=self.survey) factories.SurveyQuestionResponse.create( visit=visit2, question__survey=self.survey) factories.SurveyQuestionResponse.create( visit=visit3, question__survey=self.survey) self.responses = survey_models.SurveyQuestionResponse.objects.all()
def create_payout_finished_project(sender, instance, created, **kwargs): """ Create or update Payout for finished projects. Project finish when deadline is hit or when it's changed manually in admin. """ from localflavor.generic.validators import IBANValidator project = instance now = timezone.now() if (project.is_realised or project.is_closed) and project.amount_asked: with LocalTenant(): if now.day <= 15: next_date = timezone.datetime(now.year, now.month, 15) else: next_date = timezone.datetime(now.year, now.month, 1) + timedelta(days=20) PROJECT_PAYOUT_MODEL = get_project_payout_model() try: # Update existing Payout payout = PROJECT_PAYOUT_MODEL.objects.get(project=project) if payout.status == StatusDefinition.NEW: # Update planned payout date for new Payouts payout.calculate_amounts() payout.planned = next_date payout.save() except PROJECT_PAYOUT_MODEL.DoesNotExist: if project.campaign_started: # Create new Payout payout = PROJECT_PAYOUT_MODEL( planned=next_date, project=project ) # Calculate amounts payout.calculate_amounts() if project.is_closed: payout.status = StatusDefinition.SETTLED # Set payment details try: IBANValidator()(project.account_number) payout.receiver_account_iban = project.account_number except ValidationError as e: logger.info("IBAN error for payout id {0} and project id: {1}: {2}".format(payout.id, project.id, e.message)) payout.receiver_account_bic = project.account_bic payout.receiver_account_number = project.account_number payout.receiver_account_name = project.account_holder_name payout.receiver_account_city = project.account_holder_city payout.receiver_account_country = project.account_bank_country payout.save()
def setUp(self): self.user = get_user_model().objects.create_user( username='******', email='*****@*****.**', password='******' ) self.other_user = get_user_model().objects.create_user( username='******', email='*****@*****.**', password='******' ) self.first_question = Question.objects.create( title="Another Question", description="A not so long random text to fill this field", pub_date=timezone.datetime(2016, 1, 6, 0, 0, 0), reward=0, user=self.user, closed=False, ) self.first_answer = Answer.objects.create( question=self.first_question, answer_text="I hope this text is acceptable by django_markdown", pub_date=timezone.datetime(2016, 2, 6, 0, 0, 0), user=self.user, )
def finished_tasks(db, user): started_at = timezone.datetime(2015, 2, 9, 12, 0, 0) finished_at = timezone.datetime(2015, 2, 10, 12, 0, 0) last_longer_duration = 1 return TaskFactory.create_batch(3, user=user, started_at=started_at, finished_at=finished_at, last_longer_duration=last_longer_duration)
def get_next_planned_date(): now = timezone.now() if now.day <= 15: next_date = timezone.datetime(now.year, now.month, 15) else: next_date = timezone.datetime(now.year, now.month, 1) + relativedelta(months=1) return next_date
def get_intervals_between_dates(self, start_date, end_date): user_tz = pytz.timezone(self.category.user.profile.timezone) local_start_date = user_tz.normalize(start_date.astimezone(user_tz)) local_end_date = user_tz.normalize(end_date.astimezone(user_tz)) local_date_start = datetime( local_start_date.year, local_start_date.month, local_start_date.day, 0, 0, 0, ) local_date_end = datetime( local_end_date.year, local_end_date.month, local_end_date.day, 23, 59, 59, ) return self.interval_set.filter( start__range=( make_aware(local_date_start, user_tz), make_aware(local_date_end, user_tz) ), )
def test_event(self): _time = timezone.now() yesterday = timezone.make_aware( timezone.datetime(_time.year, _time.month, _time.day - 1)) tomorrow = timezone.make_aware( timezone.datetime(_time.year, _time.month, _time.day + 1)) evt1 = Event.objects.create(title='event1', description='desc', event_type='con', start=yesterday, is_ours=False,) evt2 = Event.objects.create(title='event2', description='desc', event_type='cha', start=yesterday, end=yesterday, is_ours=False,) evt3 = Event.objects.create(title='event3', description='desc', event_type='tra', start=yesterday, end=tomorrow, is_ours=False,) evt4 = Event.objects.create(title='event4', description='desc', event_type='tlk', start=tomorrow, is_ours=False,) self.assertEqual(evt1.is_passed(), True) self.assertEqual(evt2.is_passed(), True) self.assertEqual(evt3.is_passed(), False) self.assertEqual(evt4.is_passed(), False)
def hours_filtered(self, filter, last_month=False): #slow af function count = 0 if not last_month: for i in self.user.events.filter(hour_type=filter): count += i.hours() for i in self.user.user_events.filter(hour_type=filter): count += i.hours() else: last_month_end = timezone.datetime(timezone.now().year, timezone.now().month, 1) - timezone.timedelta(seconds=1) last_month_start = timezone.datetime(last_month_end.year, last_month_end.month, 1) for i in self.user.events.filter(hour_type=filter, date_start__gte=last_month_start, date_start__lte=last_month_end): count += i.hours() for i in self.user.user_events.filter(hour_type=filter, date_start__gte=last_month_start, date_start__lte=last_month_end): count += i.hours() """ from django.db.models import Sum userevent_count = self.user.user_events.filter(hour_type=filter).aggregate(Sum('hours_worked'))['hours_worked__sum'] if userevent_count: count += userevent_count """ return count
def dispatch(self, request, *args, **kwargs): self.month = int(kwargs.get('month')) self.year = int(kwargs.get('year')) if self.month not in range(1, 13): raise Http404 if request.method == 'POST': if request.POST.get('next'): new_date = datetime(self.year, self.month, 1) + timedelta( days=31) kwargs.update({'year': new_date.year, 'month': new_date.month}) return HttpResponseRedirect( reverse('calendar_month', kwargs=kwargs)) elif request.POST.get('previous'): new_date = datetime(self.year, self.month, 1) - timedelta( days=1) kwargs.update({'year': new_date.year, 'month': new_date.month}) return HttpResponseRedirect( reverse('calendar_month', kwargs=kwargs)) elif request.POST.get('today'): kwargs.update({'year': now().year, 'month': now().month}) return HttpResponseRedirect( reverse('calendar_month', kwargs=kwargs)) if request.is_ajax(): self.template_name = 'calendarium/partials/calendar_month.html' return super(MonthView, self).dispatch(request, *args, **kwargs)
def setUp(self): self.client = Client() building = Building.objects.create(name='main') room1 = Room.objects.create( building=building, floor=12, name='E50', capacity=8, ) Room.objects.create( building=building, floor=14, name='E17', capacity=4, ) self.reservation = Reservation.objects.create( room=room1, start=to_date_with_tz(datetime(2015, 8, 15, 11, 0)), end=to_date_with_tz(datetime(2015, 8, 15, 12, 0)), minutes=60, # TODO: should not have to specify both end and minutes )
def repl_counting_behaviors(): first_of_year = datetime(2015, 1, 1, tzinfo=pytz.utc) first_of_month = datetime(2015, 2, 1, tzinfo=pytz.utc) end_of_year = datetime(2015, 12, 31, tzinfo=pytz.utc) end_of_month = datetime(2015, 2, 28, tzinfo=pytz.utc) counting_behaviors = [ # None == Now FixedEndSlidingWindow(None, relativedelta(hours=1)), FixedEndSlidingWindow(None, relativedelta(days=2)), FixedEndSlidingWindow(None, relativedelta(days=28)), FixedEndSlidingWindow(None, relativedelta(months=1)), FixedEndSlidingWindow(None, relativedelta(months=3)), FixedEndSlidingWindow(None, relativedelta(months=6)), FixedEndSlidingWindow(None, relativedelta(years=1)), FixedEndSlidingWindow(None, relativedelta(years=1), relativedelta(months=1)), FixedStartSlidingWindow(first_of_year, relativedelta(years=1)), FixedStartSlidingWindow(first_of_month, relativedelta(years=1)), FixedStartSlidingWindow(first_of_month, relativedelta(years=1), relativedelta(months=1)), FixedWindow(first_of_month, end_of_month), FixedWindow(first_of_year, end_of_year), FixedWindow(first_of_year, end_of_year, relativedelta(months=1)), ] return counting_behaviors
def test_changelist_view_requests_count(self): """ The ``get_request_count`` context must always contain a dataset for requests-per-minute count. """ # Now assign discrete `timestamp` values. self.tracker_1.timestamp = timezone.datetime(2016, 7, 26, 23, 0) self.tracker_1.save() self.tracker_2.timestamp = timezone.datetime(2016, 7, 26, 23, 0) self.tracker_2.save() self.tracker_3.timestamp = timezone.datetime(2016, 7, 26, 23, 10) self.tracker_3.save() url = reverse('admin:tracking_analyzer_tracker_changelist') request = RequestFactory().get(url) request.user = self.user response = self.tracker_admin.changelist_view(request) data = json.loads(response.context_data['requests_count']) self.assertEqual(len(data), 2) self.assertIn( { "date": self.tracker_1.timestamp.strftime('%Y-%m-%dT%H:%M'), "requests": 2 }, data ) self.assertIn( { "date": self.tracker_3.timestamp.strftime('%Y-%m-%dT%H:%M'), "requests": 1 }, data )
def create_payout_for_fully_funded_project(sender, instance, created, **kwargs): project = instance now = timezone.now() # Check projects in phase Act that have asked for money. if project.phase == ProjectPhases.act and project.projectcampaign.money_asked: if now.day <= 15: next_date = timezone.datetime(now.year, now.month, 15) else: next_date = timezone.datetime(now.year, now.month, 1) + relativedelta(months=1) day = timezone.datetime.strftime(now, '%d%m%Y') amount = round(project.projectcampaign.money_donated * settings.PROJECT_PAYOUT_RATE) try: line = Payout.objects.get(project=project) if line.status == Payout.PayoutLineStatuses.new: line.planned = next_date line.save() except Payout.DoesNotExist: line = Payout.objects.create(planned=next_date, project=project, status=Payout.PayoutLineStatuses.new, amount=amount) organization = project.projectplan.organization line.receiver_account_bic = organization.account_bic line.receiver_account_iban = organization.account_iban line.receiver_account_number = organization.account_number line.receiver_account_name = organization.account_name line.receiver_account_city = organization.account_city line.receiver_account_country = organization.account_bank_country line.invoice_reference = 'PP' line.save() line.invoice_reference = str(project.id) + '-' + str(line.id) line.save()
def due_date(self): tz = self.created_at.tzinfo if (self.created_at < timezone.datetime(2018, 1, 7, tzinfo=tz) and self.created_at > timezone.datetime(2017, 12, 30, tzinfo=tz)): hard_coded_due_date = timezone.datetime(2018, 1, 15, tzinfo=tz) return hard_coded_due_date.date() due_dt = (self.created_at + datetime.timedelta(30)) return due_dt.astimezone(timezone.get_current_timezone()).date()
def test_time_spent(self): task = Task.objects.create() student = Student.objects.create() ts = TaskSession.objects.create( student=student, task=task, start=timezone.datetime(2017, 1, 1, 8, 0, 0, tzinfo=timezone.utc), end=timezone.datetime(2017, 1, 1, 8, 2, 5, tzinfo=timezone.utc)) assert ts.time_spent == 125
def setUp(self): self.datetime1 = timezone.datetime(year=2016, month=1, day=10, hour=12) self.datetime2 = timezone.datetime(year=2016, month=1, day=13, hour=12) self.datetime3 = timezone.datetime(year=2016, month=1, day=15, hour=12) self.word1 = create_wordtext_and_worddetails(text='car', source_name='INTERIA', occured_num=3, datetime=self.datetime1) self.word2 = create_wordtext_and_worddetails(text='bike', source_name='WP', occured_num=3, datetime=self.datetime2) self.word3 = create_wordtext_and_worddetails(text='bike', source_name='GAZETA', occured_num=1, datetime=self.datetime3)
def test_transform(): this_year = timezone.now().year Call.objects.create(headers={}, data={}) Call.objects.create(headers={}, data={}, submitted_at=timezone.datetime(2010, 10, 20)) Call.objects.create(headers={}, data={}, submitted_at=timezone.datetime(2210, 10, 20)) assert Call.objects.filter(submitted_at__year__gte=this_year).count() == 2
def test_keep_exact_match(self): start = datetime(2015, 9, 25, 18, 30) end = datetime(2015, 9, 25, 19, 0) Reservation.objects.create(room=self.room, start=start, end=end) reservations = create_reservations((start, end)) merge_reservations(self.room, reservations) self.assertEquals(1, self.room.reservation_set.count()) self.assertEquals(0, self.room.reservationlog_set.count())
def scholar_year_by(self, queryset, field_name, value): start_year = int(value[:4]) end_year = start_year + 1 start = timezone.datetime(year=start_year, month=8, day=20) end = timezone.datetime(year=end_year, month=8, day=19) return queryset.filter(**{self.datetime_field + "__gt": start, self.datetime_field + "__lt": end})
def save_model(self, request, obj, form, change): if obj.progressione_accettata: obj.dipendente.data_ultima_progressione_manuale = timezone.datetime( obj.bando.data_inizio.year, 1, 1).date() obj.dipendente.save() super().save_model(request, obj, form, change)
def get_next_scan_time_ssa(start_date, time_s, period_type, days=1): """ 获取下次执行的时间 for 数据采集 period_type: 1 自定义,2 每小时, 3 每天, 4 每周, 5 每月 6 执行一次 自定义 从 start_date + time_s 开始 每隔 days 小时 运行一次 每小时 每个小时的time_s(取分)运行一次 start_date 日期格式 time_s 时间格式 """ now = timezone.localtime(timezone.now()) time_now = timezone.datetime(now.year, now.month, now.day, now.hour, now.minute, now.second) # 秒? hour = time_s.hour minute = time_s.minute year = start_date.year month = start_date.month day = start_date.day dayth = start_date.isoweekday() # 周日为0开始算 start_time = timezone.datetime(year, month, day, hour, minute) if period_type == 1: # 自定义 从开始时间起 每隔days小时执行一次 if start_time > time_now: # 未来时间 也就是自定义时间的第一次时间 return start_time else: while start_time <= time_now: start_time = start_time + timezone.timedelta(hours=days) return start_time elif period_type == 2: # 每小时 while start_time <= time_now: start_time = start_time + timezone.timedelta(hours=1) return start_time elif period_type == 3: # 每天 while start_time <= time_now: start_time = start_time + timezone.timedelta(days=days) return start_time elif period_type == 4: # 每周 if dayth > days: delta = 7 - (dayth - days) else: delta = days - dayth return start_time + timezone.timedelta(days=delta) elif period_type == 5: # 每月 # 如果当月没有31号之类 自动算下一个月 while True: if day > days: day = days month += 1 if month == 13: month = 1 year += 1 else: day = days try: mytime = timezone.datetime(year, month, day, hour, minute) break except ValueError: month += 1 if month == 13: month = 1 year += 1 pass return mytime elif period_type == 6: # 指定时间只执行一次 return start_time
def handle(self, *args, **options): sow = self.stdout.write groups_to_make = [g.value for g in groups.Groups] existing_groups = Group.objects.all() for group in groups_to_make: if existing_groups.filter(name=group).exists(): sow(f'{group} exists') else: sow(f'{group} does not exist -- creating') Group.objects.create(name=group) # Users # ======================================== password = '******' all_users = User.objects.all() all_users.delete() # Admin sow('--- creating admin') try: admin_user = User.objects.create_superuser('admin', '', password) except IntegrityError: sow('user already exists') # Technical staff sow('--- creating tech staff') # general_group = Group.objects.get(name='technical_staff') for i in range(20): for tech_type in [Groups.LIGHT_TECHS.value, Groups.AUDIO_TECHS.value]: name = f'{tech_type}_{i}' if not User.objects.filter(username=name).exists(): user = User.objects.create_user(name, '', password) specific_group = Group.objects.get(name=tech_type) specific_group.user_set.add(user) # general_group.user_set.add(user) else: sow(f"{name} already exists") # PR managers sow('--- creating PR managers') pr_group = Group.objects.get(name=Groups.PR_MANAGERS.value) for i in range(5): name = f'pr_manager_{i}' if not User.objects.filter(username=name).exists(): user = User.objects.create_user(name, '', password) pr_group.user_set.add(user) else: sow(f"{name} already exists") # Booking managers sow('--- creating booking managers') booker_group = Group.objects.get(name=Groups.CONCERT_BOOKERS.value) for i in range(5): name = f'booking_manager_{i}' if not User.objects.filter(username=name).exists(): user = User.objects.create_user(name, '', password) booker_group.user_set.add(user) else: sow(f"{name} already exists") # Booking chiefs sow('--- creating chief booking managers') booker_group = Group.objects.get(name=Groups.CHIEF_BOOKERS.value) for i in range(5): name = f'chief_booking_manager_{i}' if not User.objects.filter(username=name).exists(): user = User.objects.create_user(name, '', password) booker_group.user_set.add(user) else: sow(f"{name} already exists") # Stages # ======================================== sow('--- creating stages') models.Stage.objects.all().delete() stage_names = [ "here", "hick", "high", "hind", "hoar", "holy", "home", "homy", "cake", "butter", "orange", "panda", "pudding", "snake" ] stage_sizes = models.Stage.STAGE_SIZE_CHOICES for name in stage_names: name = name.capitalize() + ' Stage' if not models.Stage.objects.filter(name=name).exists(): try: models.Stage.objects.create( name=f'{name}', num_seats=randint(1,10)*100, stage_costs=randint(10, 50) * 1000, stage_size=choice(stage_sizes)[0] ) except IntegrityError: sow("couldn't create stage") else: sow(f'Stage {name} already exists') # Genres # ======================================== sow('--- creating genres') genres = ['Pop', 'Gangster rap', 'Rock', 'Funk', 'Electronica'] for genre in genres: if not models.Genre.objects.filter(name=genre).exists(): try: models.Genre.objects.create(name=genre) except: sow(f"couldn't create genre {genre}") # Bands # ======================================== sow('--- creating bands') band_names = [ "Adam and the Ants", "Add N to (X)", "Adele", "The Adverts", "Akercocke", "Alabama 3", "The Alan Parsons Project", "Alien Sex Fiend", "All Saints", "AlunaGeorge", "Amy Winehouse", "Angel Witch", "The Apostles", "Archive", "Athlete", "Babyshambles", "Bad Company", "Basement Jaxx", "Bastille", "Bat For Lashes", "Benga", "Ben Howard", "Big Bang", "The Big Pink", "Billy Idol", "Blancmange", "Bleech", "Bloc Party", "Blues Incorporated", "The Bluetones", "The Bolshoi", "Bombay Bicycle Club", "Bonzo Dog Doo-Dah Band", "Bow Wow Wow", "Bush", "Busted", "Callender's Cableworks Band", "Carter The Unstoppable Sex Machine", "Chad & Jeremy", "Chase & Status", "Chris Farlowe and the Thunderbirds", "The Chords", "The Clash", "Classix Nouveaux", "Clement Marfo & The Frontline", "Client", "Coldplay", "Cream", "The Creatures", "Crystal Fighters", "Culture Club", "The Damned", "Darkstar", "Daughter", "David Bowie", "The Dave Clark Five", "Days in december", "Death in Vegas", "Deep Purple", "The Defiled", "Delilah", "Devil Sold His Soul", "Dirty Pretty Things", "Dizzee Rascal", "Django Django", "DragonForce", "Dry the River", "Dot Rotten", "Dumpy's Rusty Nuts", "Dusty Springfield", "Ebony Bones", "The Edge", "Eliza Doolittle", "Ella Mai", "Engineers", "Erasure", "Eurythmics", "Example", "The Faces", ] about_band_texts = [ "Aliquam erat volutpat.", "Nunc eleifend leo vitae magna.", "In id erat non orci commodo lobortis.", "Proin neque massa, cursus ut, gravida ut, lobortis eget, lacus.", "Sed diam.", "Praesent fermentum tempor tellus.", "Nullam tempus.", "Mauris ac felis vel velit tristique imperdiet.", "Donec at pede.", "Etiam vel neque nec dui dignissim bibendum.", "Vivamus id enim.", "Phasellus neque orci, porta a, aliquet quis, semper a, massa.", "Phasellus purus.", "Pellentesque tristique imperdiet tortor.", "Nam euismod tellus id erat.", ] legal_characters = 'abcdefghijklmnopqrstuvwxyz_' Band = models.Band Band.objects.all().delete() for band_name in band_names: if not Band.objects.filter(name=band_name).exists(): manager_name = band_name.lower() new_manager_name = '' for (i,c) in enumerate(manager_name): if c in legal_characters: new_manager_name += c else: new_manager_name += '_' new_manager_name += '_manager' sow(f'{new_manager_name}') if User.objects.filter(username=new_manager_name).exists(): manager = User.objects.get(username=new_manager_name) else: manager = User.objects.create_user(new_manager_name, '', password) manager.is_staff = True manager.save() Band.objects.create(name=band_name, manager=manager, about_band=choice(about_band_texts), genre=choice(models.Genre.objects.all())) # Concerts # ======================================== sow('--- creating concerts') Concert = models.Concert Concert.objects.all().delete() models.TechnicalNeed.objects.all().delete() taglines = [' - A New Hope', ' Strike Back', ' Return', ' II', ' III', ' IV'] times = [] now = timezone.now() year = now.year years = list(range(year - 5, year + 2)) months = [(now.month + i) % 12 for i in range(1)] days = [(now.day + i) % 28 for i in range(-5, 6)] hours = [16, 18, 20, 22] for year in years: times.append(now.replace(year=year)) stages = models.Stage.objects.all() genres = models.Genre.objects.all() light_techs = Group.objects.get(name=Groups.LIGHT_TECHS.value).user_set.all() audio_techs = Group.objects.get(name=Groups.AUDIO_TECHS.value).user_set.all() # Requirements audio_reqs = ['speakers', 'microphones', 'monitors', 'guitars', 'keyboards'] light_reqs = ['spotlights', 'red lights', 'green lights', 'blue lights', 'yellow lights'] other_reqs = ['water bottles', 'pink mentos'] for band in models.Band.objects.all(): sow(f"{band}") for _ in range(randint(0,5)): tagline = choice(taglines) concert_time=timezone.datetime( choice(years), choice(months), choice(days), choice(hours), tzinfo=now.tzinfo, ) concert = Concert.objects.create( name=f'{band.name} {tagline}', band_name=band, stage_name=choice(stages), genre_music=choice(genres), ticket_price=randint(100,1000), concert_time=concert_time, ) concert.light_tech = choices(light_techs, k=randint(1,5)) concert.sound_tech = choices(audio_techs, k=randint(1,5)) concert.save() # Make technical requirements sound = '' for req in choices(audio_reqs, k=randint(0, len(audio_reqs) + 1)): sound += f'- {randint(1,10)} {req}\n' light = '' for req in choices(light_reqs, k=randint(0, len(light_reqs) + 1)): light += f'- {randint(1,10)} {req}\n' other = '' for req in choices(other_reqs, k=randint(0, len(other_reqs) + 1)): other += f'- {randint(1,10)} {req}\n' tech_req = models.TechnicalNeed.objects.create( concert_name=concert, sound=sound, light=light, other_technical_needs=other ) # Festivals # ======================================== Festival = models.Festival Festival.objects.all().delete() names = ['Testivalen'] for year in years: for name in names: full_name = f'{name} {year}' if not Festival.objects.filter(name=full_name).exists(): festival = Festival.objects.create(name=full_name) festival.concerts = Concert.objects.filter(concert_time__year=year) festival.save()
def test_humanize_absolute_date(self): test_cases = [ (timezone.datetime(2021, 1, 1), timezone.datetime(2023, 1, 1), '01/01/2021'), (timezone.datetime(2021, 1, 1), timezone.datetime(2021, 2, 1), '01/01/2021'), (timezone.datetime(2021, 1, 1), timezone.datetime(2021, 1, 8), '01/01/2021'), (timezone.datetime(2021, 1, 1), timezone.datetime(2021, 1, 7), 'Friday'), (timezone.datetime(2021, 1, 1), timezone.datetime(2021, 1, 7, 23, 59), 'Friday'), (timezone.datetime(2021, 1, 1), timezone.datetime(2021, 1, 3), 'Friday'), (timezone.datetime(2021, 1, 1), timezone.datetime(2021, 1, 2), 'Yesterday'), (timezone.datetime(2021, 1, 1), timezone.datetime(2021, 1, 2, 23, 59), 'Yesterday'), (timezone.datetime(2021, 1, 1), timezone.datetime(2021, 1, 1), 'Today'), ] for test_case in test_cases: result = humanize_absolute_date(test_case[0], test_case[1]) self.assertEqual(test_case[2], result)
def digest_data(): # open the csv we want to read my_target_data_file = os.path.join(settings.BASE_DIR, 'scuba', '2019_data_import.csv') with open(my_target_data_file, 'r') as csv_read_file: my_csv = csv.DictReader(csv_read_file) for row in my_csv: # REGION region_dict = dict( AB="Anse-Bleue", CG="Cocagne (aka God’s place)", CQ="Caraquet", FH="Fox Harbor", GA="Grande-Anse", MC="Murray Corner", NG="Neguac", PH="Pigeon Hill", PV="Pointe-Verte", RB="Richibucto", RO="Robichaud", SC="Shediac", TB="Tabusintac", TR="Toney River", ) region_abbrev = row['Region'] region_name = region_dict[region_abbrev] # we want to crash is nothing is found. region, created = models.Region.objects.get_or_create(name=region_name, abbreviation=region_abbrev) # SITE site_name = row['Site'].upper() site, created = models.Site.objects.get_or_create( name=site_name, abbreviation=site_name, region=region ) # TRANSECT transect_name = row['Transect'].upper() transect, created = models.Transect.objects.get_or_create( name=transect_name, site=site ) # SAMPLE year = int(row['Année']) month = int(row['Mois']) day = int(row['Jour']) dt = make_aware(timezone.datetime(year, month, day), timezone=pytz.timezone("Canada/Atlantic")) sample, created = models.Sample.objects.get_or_create( site=site, datetime=dt ) # DIVER diver_dict = dict( arondeau="Amélie Rondeau", bcomeau="Bruno Comeau", dgiard="David Giard", elandry="Éric Landry", fplante="François Plante", fsavoie="Fernand Savoie", glandry="Germain Landry", gpaulin="Gilles Paulin", grobichaud="Guy Robichaud", mcomeau="Michel Comeau", mcousino="Maryse Cousineau", mouellet="Maxime Ouellet", rdoucette="Renelle Doucette", rfrigo="Renaud Frigault", rvienneau=" Réjean Vienneau", sleblanc="Stépan Leblanc", slevesque="Sylvie Lévesque", yhache="Yvon Haché", phanley="Patricia Hanley", krobertson="Karen Robertson", nasselin="Natalie Asselin", ) mushed_name = row['Plongeur'].lower().strip() name = diver_dict[mushed_name] diver, created = models.Diver.objects.get_or_create( first_name=name.split(" ")[0], last_name=name.split(" ")[1] ) # DIVE heading_txt = row['Heading'].lower() side_txt = row['Side'].lower() heading = heading_txt[0] if not heading_txt[0] == "u" else None side = side_txt[0] if not side_txt[0] == "u" else None dive, created = models.Dive.objects.get_or_create( sample=sample, diver=diver, transect=transect, heading=heading, side=side, width_m=row['Width (m)'], ) # SECTION sand = float(row['Sa']) if is_number_tryexcept(row['Sa']) else 0 mud = float(row['Va']) if is_number_tryexcept(row['Va']) else 0 hard = float(row['Du']) if is_number_tryexcept(row['Du']) else 0 algae = float(row['Al']) if is_number_tryexcept(row['Al']) else 0 gravel = float(row['Gr']) if is_number_tryexcept(row['Gr']) else 0 cobble = float(row['Co']) if is_number_tryexcept(row['Co']) else 0 pebble = float(row['Ca']) if is_number_tryexcept(row['Ca']) else 0 try: section, created = models.Section.objects.get_or_create( dive=dive, interval=row['section'], depth_ft=row['Depth_(ft)'] if is_number_tryexcept(row['Depth_(ft)']) else None, comment=row['Comments'], percent_sand=sand, percent_mud=mud, percent_hard=hard, percent_algae=algae, percent_gravel=gravel, percent_cobble=cobble, percent_pebble=pebble, ) except IntegrityError as E: # comment = row[ # 'Comments'] + f"; There is a problem with the source data: the diver's description of substrate is not consistent between observations (rows)" section = models.Section.objects.get( dive=dive, interval=row['section'], depth_ft=row['Depth_(ft)'] if is_number_tryexcept(row['Depth_(ft)']) else None, ) section_comment = "There is a problem with the source data: the diver's description of substrate is not consistent between observations (rows)" if not section.comment: section.comment = section_comment elif section_comment in section.comment: pass else: section.comment += f'; {section_comment}' section.save() dive_comment = f"There is a problem with the source data: the diver's description of substrate is not " \ f"consistent between observations (rows): please see section interval #{row['section']}" if not dive.comment: dive.comment = dive_comment elif dive_comment in dive.comment: pass else: dive.comment += f'; {dive_comment}' dive.save() # print(E, section, dive) # OBSERVATIONS # sex sex_txt_orig = row['sexe'] sex_txt = row['sexe'].lower().strip().replace(" ", "").replace("-", "") sex = None if sex_txt in ["m", "f"]: sex = sex_txt else: sex = 'u' egg_status = None if sex_txt in ["b", "b1", "b2", "b3", "b4"]: egg_status = sex_txt sex = 'f' length_txt_orig = row['LC_(mm)'] length_txt = row['LC_(mm)'].strip().replace("?", "").replace("~", "") length = None if is_number_tryexcept(length_txt): length = float(length_txt) if length: # uncertainty certainty = 1 # will deem the observation uncertain if there is a tilda in the lenth OR length is > 20 and sex is not known. certainty_reason = None if "~" in row['LC_(mm)']: certainty = 0 certainty_reason = "Observation deemed uncertain because of tilda in length field." elif length > 20 and sex == 'u': certainty = 0 certainty_reason = "Observation deemed uncertain because > 20mm but sex is not known." comment = f"Imported from MS Excel on {timezone.now().strftime('%Y-%m-%d')}. Original data: sex={sex_txt_orig}, length={length_txt_orig}." if certainty_reason: comment += f" {certainty_reason}" models.Observation.objects.create( section=section, sex=sex, egg_status=egg_status, carapace_length_mm=length, comment=comment, certainty_rating=certainty, ) else: # lets make a comment about this entry in the section comment = f"Row in excel spreadsheet did not result in an observation. Here is the original data: sex={sex_txt_orig}, length={length_txt_orig}" if section.comment: section.comment += f"; {comment}" else: section.comment = comment section.save()
def test_check_day_statistics_generation_fail(self, now_mock): now_mock.return_value = timezone.make_aware( timezone.datetime(2000, 1, 3)) self.assertIsInstance(check_day_statistics_generation(), MonitoringStatusIssue)
def handle(self, *args, **options): INSTALLATION_TYPES = ( ('solar-canopy', 'Solar - Canopy'), ('solar-rooftop', 'Solar - Roof Top Mount'), ('solar-wall', 'Solar - Wall Mount'), ('solar-ground-pole', 'Solar - Ground or Pole Mount'), ('solar-building-photovoltaic', 'Solar - Building Integrated Photovoltaic'), ('solar-other', 'Solar - Other'), ('wind-horizontal', 'Wind - Horizontal Axis'), ('wind-horizontal', 'Wind - Vertical Axis'), ('hydroelectric', 'Low Impact Hydroelectric'), ) # Create Installation choices installation_types = {} for _, name in INSTALLATION_TYPES: installation_types[name] = GreenPowerInstallation.objects.create(name=name) FINANCE_TYPES = ( ('operating-budget', 'Operating budget'), ('endowment', 'Endowment'), ('capital-budget', 'Capital budget'), ('third-party', 'Third party'), ('donation', 'Donation'), ) finance_types = {} for _, name in FINANCE_TYPES: finance_types[name] = GreenPowerFinanceOption.objects.create(name=name) ownership_types = dict([(o[1], o[0]) for o in GreenPowerProject.OWNERSHIP_TYPES]) LOCATION_CHOICES = ( ('institution-owned-main', 'Institution-owned property (main campus)'), ('institution-owned-remote', 'Institution-owned property (remote)'), ('Third party-owned', 'Third party-owned property'), ('unknown', 'Unknown'), ) location_options = {} for _, name in LOCATION_CHOICES: location_options[name] = GreenPowerLocation.objects.create(name=name) user_monika = User.objects.get(email='*****@*****.**') energy_topic = SustainabilityTopic.objects.get(slug='energy') with open("{}/{}".format(os.path.dirname(__file__), 'green_power_projects.csv'), 'rb') as csvfile: reader = csv.DictReader(csvfile) for row in reader: install_type1 = row['Installation Type 1'] install_type2 = row['Installation Type 2'] install_type3 = row['Installation Type 3'] cost = row['Installed Cost (U.S. Dollars)'].replace(',', '').replace('$', '') if cost: cost = int(cost) else: cost = None annual_prod = row['Approximate Annual Production (kWh)'].replace(',', '') if annual_prod: annual_prod = int(annual_prod) else: annual_prod = None _d = [int(p) for p in row['Date Posted'].split('/')] date_submitted = timezone.datetime(_d[2], _d[0], _d[1]) _d = [int(p) for p in row['Date Installed'].split('/')] date_installed = datetime(_d[2], _d[0], _d[1]) new_gpp = GreenPowerProject( title=row['Project Name'], description=row['Project Overview'], project_size=int(row['Project Size (kW)'].replace(',', '')), annual_production=annual_prod, installed_cost=cost, ownership_type=ownership_types[row['Ownership type']], date_created=date_installed, date_submitted=date_submitted, published=date_submitted, status='published' ) new_gpp.save() # # Installations # first = installation_types[install_type1] new_gpp.installations.add(first) if install_type2: new_gpp.installations.add(installation_types[install_type2]) if install_type3: new_gpp.installations.add(installation_types[install_type3]) # # Locations # # default to Unknown new_gpp.locations.add(location_options['Unknown']) # # Organizations # for idx in (1, 2, 3, 4): org_id = row['Organization{}_ID'.format(idx)] if org_id: org = Organization.objects.get(account_num=org_id) new_gpp.organizations.add(org) # # Topic # new_gpp.topics.add(energy_topic) # Tags tags_token = row['Tag(s)'] tags = [tag.strip() for tag in tags_token.split(',')] for tag in tags: new_gpp.keywords.add(tag) # Project Contact if row['ProjectContact-Name']: Author.objects.create( ct=new_gpp, name=row['ProjectContact-Name'], title=row['ProjectContact-Title'], organization_id=int(row['ProjectContact-OrgID']) ) # # Uploads # if row['Upload 1']: create_file_from_url(new_gpp, row['Upload 1']) if row['Upload 2']: create_file_from_url(new_gpp, row['Upload 2']) # # URLs / Websites # for i in range(1, 6): url = row['URL{}'.format(i)] if url: Website.objects.create( url=url, ct=new_gpp ) # # Submitter # submitter_email = row['Submitter email'] try: submitter_user = User.objects.get(email=submitter_email) except User.DoesNotExist: submitter_user = user_monika new_gpp.submitted_by = submitter_user new_gpp.save()
class Invitation(BaseModel): invite_id = models.SlugField(editable=False, unique=True, default=id_generator) with_guest = models.BooleanField(default=False, verbose_name="Invite additional guest (+1)") family_size = models.IntegerField(default=0) family_rsvp = models.CharField(max_length=200, choices=rsvp_choices, default='Maybe') family_rsvp_number = models.IntegerField(default=0) personal_message = models.TextField(max_length=400, default="", blank=True) invitation_name = models.CharField(max_length=200, default="", blank=True) date_opened = models.DateTimeField(default=timezone.datetime(2000, 1, 1)) was_opened = models.BooleanField(default=False) side = models.CharField(max_length=200, choices=side_choices, default='Both') group = models.CharField(max_length=200, choices=group_choices, blank=True) couple = models.BooleanField(default=True) def set_invite_to_default(self): self.family_rsvp = "Maybe" self.family_rsvp_number = 0 self.personal_message = '' self.date_opened = timezone.datetime(2000, 1, 1) self.was_opened = False for person in self.person_list(): person.person_rsvp = "Maybe" person.is_vegan = False person.diet_info = '' person.needs_ride_location = '' person.has_car_room_location = '' person.number_of_seats = 0 person.email_app = '' person.phone_app = '' person.save() self.save() def invitation_type(self): """ Returns the invitation type. -- Guest means that there is an extra person to the invitation who is a guest. -- Family means that we are just inputting the family name and size and the invite has one person just for the info. -- People type means the invitation includes a list of people """ if self.with_guest: return "Guest" elif self.family_size > 0: return "Family" else: return "People" def invitation_total_rsvp(self): """Total people who are coming""" total_rsvp = 0 if self.family_size and self.family_rsvp == "Yes": return self.family_rsvp_number people = Person.objects.filter(invitation=self.id) for person in people: if person.person_rsvp == "Yes": total_rsvp += 1 return total_rsvp def invitation_total_invited(self): total_invited = 0 if self.family_size: return self.family_size people = Person.objects.filter(invitation=self.id) for _ in people: total_invited += 1 return total_invited def create_guest(self, is_english): if not self.has_guest_person(): guest = Person() guest.invitation = self if is_english: guest.name = "Guest" else: guest.name = "אורח/ת" guest.save() self.save() def is_english(self): for person in self.person_list(): if str_is_english(person.name): return True def __str__(self): return str(self.id) def has_guest_person(self): people = Person.objects.filter(invitation=self.id) for person in people: if person.is_guest(): return True return False def person_list(self): person_list = list(self.person_set.all()) for person in person_list[:]: if person.is_guest(): person_list.remove(person) person_list.append(person) return person_list def has_rsvped(self): for person in self.person_list(): if person.person_rsvp in {"Yes", "No"}: return True return False def invitation_url(self): return "http://www.gavrielawedding.com/invitation/" + self.invite_id def person_coming_list(self): coming_list = [] for person in self.person_list(): if person.is_coming(): coming_list.append(person) return coming_list def needs_rsvp(self): invite_needs_rsvp = False for person in self.person_list(): if not person.has_rsvp(): invite_needs_rsvp = True return invite_needs_rsvp def has(self, rsvp): for person in self.person_list(): if person.person_rsvp == rsvp: return True return False def total_yes(self): """Total people who are coming""" return self.total_rsvp("Yes") def total_maybe(self): """Total people who are coming""" return self.total_rsvp("Maybe") def total_no(self): """Total people who are coming""" return self.total_rsvp("No") def total_rsvp(self, rsvp): """Total people who are coming""" total_rsvp = 0 people = Person.objects.filter(invitation=self.id) for person in people: if person.person_rsvp == rsvp: total_rsvp += 1 return total_rsvp
def year_statistics(target_date): """ Alias of daterange_statistics() for a year targeted. """ start_of_year = timezone.datetime(year=target_date.year, month=1, day=1) end_of_year = timezone.datetime.combine( start_of_year + relativedelta(years=1), time.min) return range_statistics(start=start_of_year, end=end_of_year)
def test_check_day_statistics_generation_okay(self, now_mock): now_mock.return_value = timezone.make_aware( timezone.datetime(2000, 1, 2)) self.assertEqual(check_day_statistics_generation(), None)
def test_local_to_date(self): local_date = datetime(2018, 3, 12, 11, 20, 20) self.assertEqual( timezone.datetime(2018, 3, 12, 10, 20, 20, tzinfo=timezone.utc), local_to_date(local_date))
def build_stat_results(keyword=None): """Buidl the results page context. Args: keyword (str): The keyword to build statistic results. """ from dashboard.models import Bounty, HackathonEvent, Tip context = { 'active': 'results', 'title': _('Results'), 'card_desc': _('Gitcoin is transparent by design. Here are some stats about our suite of OSS incentivization products.'), } pp = PerformanceProfiler() pp.profile_time('start') base_alumni = Alumni.objects.all().cache() base_bounties = Bounty.objects.current().filter(network='mainnet').cache() base_leaderboard = LeaderboardRank.objects.filter(product='all').cache() pp.profile_time('filters') if keyword: base_email_subscribers = EmailSubscriber.objects.filter(keywords__icontains=keyword).cache() base_profiles = base_email_subscribers.select_related('profile') base_bounties = base_bounties.filter(raw_data__icontains=keyword).cache() profile_pks = base_profiles.values_list('profile', flat=True) profile_usernames = base_profiles.values_list('profile__handle', flat=True) profile_usernames = list(profile_usernames) + list([bounty.github_repo_name for bounty in base_bounties]) base_alumni = base_alumni.filter(profile__in=profile_pks) base_leaderboard = base_leaderboard.filter(github_username__in=profile_usernames) context['alumni_count'] = base_alumni.count() pp.profile_time('alumni') from marketing.models import EmailSubscriber, EmailEvent # todo: add preferences__suppression_preferences__roundup ? total_count = EmailSubscriber.objects.count() count_active_30d = EmailEvent.objects.filter(event='open', created_on__gt=(timezone.now() - timezone.timedelta(days=30))).distinct('email').count() count_active_90d = EmailEvent.objects.filter(event='open', created_on__gt=(timezone.now() - timezone.timedelta(days=90))).distinct('email').count() count_active_90d -= count_active_30d count_inactive = total_count - count_active_30d - count_active_90d context['pct_inactive'] = round(100 * count_inactive / total_count) context['pct_active_90d'] = round(100 * count_active_90d / total_count) context['pct_active_30d'] = round(100 * count_active_30d / total_count) context['count_inactive'] = count_inactive context['count_active_90d'] = count_active_90d context['count_active_30d'] = count_active_30d pp.profile_time('count_*') from quests.models import Quest num_quests = 15 top_quests = Quest.objects.filter(visible=True).order_by('-ui_data__attempts_count')[0:num_quests] context['top_quests'] = [{ 'title': quest.title, 'url': quest.url, 'plays': quest.ui_data.get('attempts_count', 0), 'img': quest.enemy_img_url, } for quest in top_quests] # Leaderboard num_to_show = 30 context['top_funders'] = base_leaderboard.filter(active=True, leaderboard='quarterly_payers') \ .order_by('rank').values_list('github_username', flat=True)[0:num_to_show] pp.profile_time('funders') context['top_orgs'] = ['ethereumclassic', 'web3foundation', 'ethereum', 'arweave', 'zilliqa'] pp.profile_time('orgs') context['top_coders'] = base_leaderboard.filter(active=True, leaderboard='quarterly_earners') \ .order_by('rank').values_list('github_username', flat=True)[0:num_to_show] pp.profile_time('orgs') # community size _key = 'email_subscriberse' if not keyword else f"subscribers_with_skill_{keyword}" base_stats = Stat.objects.filter(key=_key).order_by('-pk').cache() context['members_history'], context['slack_ticks'] = get_history(base_stats, "Members") pp.profile_time('Stats1') # jdi history key = f'joe_dominance_index_30_{keyword}_value' if keyword else 'joe_dominance_index_30_value' base_stats = Stat.objects.filter( key=key, ).order_by('-pk').cache() num_months = int((timezone.now() - timezone.datetime(2017, 10, 1).replace(tzinfo=pytz.UTC)).days/30) context['jdi_history'], __ = get_history(base_stats, 'Percentage', num_months) pp.profile_time('Stats2') # bounties history cumulative = False bounty_history = get_bounty_history(keyword, cumulative) context['bounty_history'] = json.dumps(bounty_history) pp.profile_time('bounty_history') def get_kudos_leaderboard(key='kudos_token.artist'): query = f""" select replace({key}, '@', '') as theusername, sum(kudos_kudostransfer.amount) as amount, string_agg( DISTINCT kudos_kudostransfer.kudos_token_cloned_from_id::varchar(255), ','), count(1) as num from kudos_kudostransfer inner join kudos_token on kudos_kudostransfer.kudos_token_cloned_from_id = kudos_token.id where {key} != '' group by theusername order by amount desc limit 10 """ with connection.cursor() as cursor: cursor.execute(query) rows = [] for row in cursor.fetchall(): _row = [ele for ele in row] # cast to array _row[2] = _row[2].split(',') rows.append(_row) return rows # Bounties from marketing.models import ManualStat completion_rate = get_completion_rate(keyword) pp.profile_time('completion_rate') funder_receiver_stats = get_funder_receiver_stats(keyword) pp.profile_time('funder_receiver_stats') context['kudos_leaderboards'] = [ ['Top Kudos Artists 👩🎨', get_kudos_leaderboard('kudos_token.artist'), 'created'], ['Top Kudos Collectors 🖼', get_kudos_leaderboard('kudos_kudostransfer.username'), 'collected'], ['Top Kudos Senders 💌', get_kudos_leaderboard('kudos_kudostransfer.from_username'), 'sent'] ] pp.profile_time('kudos_leaderboard') context['funders'] = funder_receiver_stats['funders'] context['avg_value'] = funder_receiver_stats['avg_value'] context['median_value'] = funder_receiver_stats['median_value'] context['transactions'] = funder_receiver_stats['transactions'] context['recipients'] = funder_receiver_stats['recipients'] pp.profile_time('funder_receiver_stats2') context['mau'] = ManualStat.objects.filter(key='MAUs').order_by('-pk').values_list('val', flat=True)[0] context['audience'] = json.loads(context['members_history'])[-1][1] pp.profile_time('audience') bounty_abandonment_rate = round(100 - completion_rate, 1) total_bounties_usd = sum(base_bounties.exclude(idx_status__in=['expired', 'cancelled', 'canceled', 'unknown']).values_list('_val_usd_db', flat=True)) total_tips_usd = sum([ tip.value_in_usdt for tip in Tip.objects.filter(network='mainnet').send_happy_path() if tip.value_in_usdt ]) total_grants_usd = get_grants_history_at_date(timezone.now(), []) total_kudos_usd = get_kudos_history_at_date(timezone.now(), []) total_codefund_usd = get_codefund_history_at_date(timezone.now(), '') all_platforms = [ float(total_bounties_usd), float(total_tips_usd), float(total_grants_usd), float(total_kudos_usd), float(total_codefund_usd) ] context['universe_total_usd'] = sum(all_platforms) pp.profile_time('universe_total_usd') context['max_bounty_history'] = float(context['universe_total_usd']) * .15 context['bounty_abandonment_rate'] = bounty_abandonment_rate bounty_average_turnaround = round(get_bounty_median_turnaround_time('turnaround_time_submitted', keyword) / 24, 1) context['bounty_average_turnaround'] = f'{bounty_average_turnaround} days' pp.profile_time('bounty_average_turnaround') context['hourly_rate_distribution'] = get_hourly_rate_distribution(keyword) context['hourly_rate_distribution_by_range'] = {} usd_value_ranges = [[10, 50], [50, 150], [150, 500], [500, 1500], [1500, 5000], [5000, 50000]] for val_range in usd_value_ranges: low = val_range[0] if val_range[0] < 1000 else f"{round(val_range[0]/1000,1)}k" high = val_range[1] if val_range[1] < 1000 else f"{round(val_range[1]/1000,1)}k" key = f"${low} to ${high}" context['hourly_rate_distribution_by_range'][key] = get_hourly_rate_distribution(keyword, val_range, 'quartile') context['skill_rate_distribution_by_range'] = {} for programming_language in programming_languages: context['skill_rate_distribution_by_range'][programming_language] = get_hourly_rate_distribution(programming_language, None, 'quartile') context['bounty_claimed_completion_rate'] = completion_rate context['bounty_median_pickup_time'] = round( get_bounty_median_turnaround_time('turnaround_time_started', keyword), 1) pp.profile_time('bounty_median_pickup_time') from kudos.models import Token as KudosToken context['kudos_tokens'] = KudosToken.objects.filter(num_clones_in_wild__gt=0).order_by('-num_clones_in_wild')[0:25] context['kudos_tokens'] = [{ 'name': kt.humanized_name, 'url': kt.url, 'static_image': kt.preview_img_url, } for kt in context['kudos_tokens']] pp.profile_time('kudos_tokens') pp.profile_time('final') context['keyword'] = keyword total_gmv_rounded = f"${round(context['universe_total_usd'] / 1000000, 1)}m" context['total_gmv_rounded'] = total_gmv_rounded context['title'] = f"{total_gmv_rounded} in " + f"{keyword.capitalize() if keyword else ''} Results" context['programming_languages'] = ['All'] + programming_languages try: context['pct_breakeven'] = ManualStat.objects.filter(key='pct_breakeven').values_list('val', flat=True)[0] except Exception as e: print(e) context['pct_breakeven'] = 0 context['pct_not_breakeven'] = 100 - context['pct_breakeven'] # last month data today = timezone.now() first = today.replace(day=1) lastMonth = first - timezone.timedelta(days=1) context['prev_month_name'] = lastMonth.strftime("%B %Y") context['prev_month_name_short'] = lastMonth.strftime("%B") bh = bounty_history[-1] if context['prev_month_name'] == bounty_history[-1][0] else bounty_history[-2] bh[0] = 0 context['last_month_amount'] = round(sum(bh)/1000) context['last_month_amount_hourly'] = sum(bh) / 30 / 24 context['last_month_amount_hourly_business_hours'] = context['last_month_amount_hourly'] / 0.222 context['hackathons'] = [(ele, ele.stats) for ele in HackathonEvent.objects.filter(visible=True, start_date__lt=timezone.now()).order_by('-start_date').all()] context['hackathon_total'] = sum([ele[1]['total_volume'] for ele in context['hackathons']]) from dashboard.models import FeedbackEntry reviews = FeedbackEntry.objects.exclude(comment='').filter(created_on__lt=(timezone.now() - timezone.timedelta(days=7))).order_by('-created_on')[0:15] context['reviews'] = [(ele.rating, ele.anonymized_comment) for ele in reviews] context['ratings'] = [1, 2, 3, 4, 5] context['num_grants'] = Grant.objects.filter(hidden=False, active=True).count() grants_gmv = Stat.objects.filter(key='grants').order_by('-pk').first().val context['grants_gmv'] = str(round(grants_gmv / 10**6, 2)) + "m" num_contributions = Contribution.objects.count() from dashboard.models import BountyFulfillment context['hours'] = sum(BountyFulfillment.objects.filter(fulfiller_hours_worked__isnull=False, bounty__current_bounty=True, fulfiller_hours_worked__lt=1000).values_list('fulfiller_hours_worked', flat=True)) context['no_contributions'] = num_contributions context['no_bounties'] = Bounty.objects.current().count() context['no_tips'] = Tip.objects.filter(network='mainnet').send_happy_path().count() context['ads_gmv'] = get_codefund_history_at_date(timezone.now(), '') context['ads_gmv'] = str(round(context['ads_gmv'] / 10**3, 1)) + "k" context['bounties_gmv'] = Stat.objects.filter(key='bounties_done_value').order_by('-pk').first().val context['bounties_gmv'] = str(round((total_tips_usd + context['bounties_gmv']) / 10**6, 2)) + "m" median_index = int(num_contributions/2) context['median_contribution'] = round(Contribution.objects.order_by("subscription__amount_per_period_usdt")[median_index].subscription.amount_per_period_usdt, 2) context['avg_contribution'] = round(grants_gmv / num_contributions, 2) from grants.views import clr_round context['num_matching_rounds'] = clr_round context['ads_served'] = str(round(ManualStat.objects.filter(key='ads_served').order_by('-pk').first().val / 10**6, 1)) + "m" context['privacy_violations'] = ManualStat.objects.filter(key='privacy_violations').order_by('-pk').first().val return context
def __init__(self, res_date): self.res_date = res_date self.today = dateparse.parse_date(res_date) if res_date else timezone.now() self.res_date_previous = timezone.datetime(self.today.year, self.today.month, self.today.day-1, 0).strftime("%Y-%m-%d") self.res_date_next = timezone.datetime(self.today.year, self.today.month, self.today.day+1, 0).strftime("%Y-%m-%d")
def default_start_date(): d = timezone.localdate() return timezone.datetime(d.year, d.month, d.day, 8, 0, 0, tzinfo=timezone.utc)
def save(self, *args, **kwargs): d = datetime(year=self.ntime.year, month=self.ntime.month, day=1) archive, _ = Archive.objects.get_or_create(user=self.author, date=d) self.archive = archive super().save(*args, **kwargs)
HACKATHON_TWITTER_ACCOUNT = 'ugahacks/' # (OPTIONAL) Hackathon Facebook page HACKATHON_FACEBOOK_PAGE = 'ugahacks/' # (OPTIONAL) Hackathon YouTube channel HACKATHON_YOUTUBE_PAGE = 'UCudlu7Tfg7VL7sR5NJzcCnw' # (OPTIONAL) Hackathon Instagram user HACKATHON_INSTAGRAM_ACCOUNT = 'ugahacks/' # (OPTIONAL) Hackathon Medium user HACKATHON_MEDIUM_ACCOUNT = '' # (OPTIONAL) Github Repo for this project (so meta) HACKATHON_GITHUB_REPO = 'https://github.com/ugahacks/myugahacks/' # (OPTIONAL) Slack Workspace for the event HACKATHON_SLACK = 'https://slack.ugahacks.com/' # (OPTIONAL) Applications deadline HACKATHON_APP_DEADLINE = timezone.datetime( 2021, 2, 5, 13, 00, tzinfo=timezone.pytz.timezone(TIME_ZONE)) # (OPTIONAL) Online Check-in deadline CHECKIN_DEADLINE = timezone.datetime(2021, 2, 5, 19, 00, tzinfo=timezone.pytz.timezone(TIME_ZONE)) # (OPTIONAL) When to arrive at the hackathon # HACKATHON_ARRIVE = 'Check-in opens at 5:00 PM and the opening ceremony will be at 6:30 PM on February 5th at the Zell B. Miller Center. ' \ # 'Further details about the schedule can be found at 6.ugahacks.com. We hope to see you there!' # (OPTIONAL) When to arrive at the hackathon # HACKATHON_LEAVE = 'Closing ceremony will be held on Sunday, February 7th at 1:00 PM. ' \ # 'However the projects expo fair will be held in the morning from 10:00 AM to 1:00 PM.' # (OPTIONAL) Hackathon event page HACKATHON_EVENT_PAGE = 'https://6.ugahacks.com/'
def test_to_timestamp(self): value = timezone.datetime(2002, 5, 3, tzinfo=timezone.utc) base62_value = signing.UserSigner.to_timestamp(value=value) assert base62_value == "173QUS"
def build_stat_results(): from dashboard.models import Bounty """Buidl the results page context.""" context = { 'active': 'results', 'title': _('Results'), 'card_desc': _('Gitcoin is transparent by design. Here are some stats about our core bounty product.'), } base_bounties = Bounty.objects.current().filter(network='mainnet') context['alumni_count'] = Alumni.objects.count() context['count_open'] = base_bounties.filter(network='mainnet', idx_status__in=['open']).count() context['count_started'] = base_bounties.filter(network='mainnet', idx_status__in=['started', 'submitted']).count() context['count_done'] = base_bounties.filter(network='mainnet', idx_status__in=['done']).count() # Leaderboard context['top_orgs'] = LeaderboardRank.objects.filter(active=True, leaderboard='quarterly_orgs').order_by('rank').values_list('github_username', flat=True) #community size base_stats = Stat.objects.filter( key='email_subscriberse', ).order_by('-pk') today = base_stats.first().val context['members_history'] = ([ ['Year', 'Members'], ['Launch', 0], ['6 months ago', base_stats.filter(created_on__lt=(timezone.now() - timezone.timedelta(days=6*30))).first().val], ['5 months ago', base_stats.filter(created_on__lt=(timezone.now() - timezone.timedelta(days=5*30))).first().val], ['4 months ago', base_stats.filter(created_on__lt=(timezone.now() - timezone.timedelta(days=4*30))).first().val], ['3 months ago', base_stats.filter(created_on__lt=(timezone.now() - timezone.timedelta(days=3*30))).first().val], ['2 months ago', base_stats.filter(created_on__lt=(timezone.now() - timezone.timedelta(days=2*30))).first().val], ['1 month ago', base_stats.filter(created_on__lt=(timezone.now() - timezone.timedelta(days=1*30))).first().val], ['Today', today] ]) context['members_history'] = json.dumps(context['members_history']) # bounties hisotry context['bounty_history'] = [ ['', 'Open / Available', {'role': 'annotation'}, 'Claimed / In Progress', { 'role': 'annotation' }, 'Completed', { 'role': 'annotation' }, 'CodeFund Bounties' ], ["January 2018", 903, "Open", 2329, "Started", 5534, "Completed", 1203], ["February 2018", 1290, "Open", 1830, "Started", 15930, "Completed", 1803], ["March 2018", 6903, "Open", 4302, "Started", 16302, "Completed", 2390], ["April 2018", 5349, "Open", 5203, "Started", 26390, "Completed", 3153], ["May 2018", 6702, "Open", 4290, "Started", 37342, "Completed", 4281], ] for year in range(2018, 202): months = range(1, 12) if year == 2018: months = range(6, 12) for month in months: then = timezone.datetime(year, month, 3) if then < timezone.now(): row = get_bounty_history_row(then.strftime("%M/%y"), then) context['bounty_history'].append(row) context['bounty_history'] = json.dumps(context['bounty_history']) # slack ticks increment = 1000 context['slack_ticks'] = list(x * increment for x in range(0, int(today/increment)+1)) context['slack_ticks'] = json.dumps(context['slack_ticks']) # Bounties # TODO: make this info dynamic context['universe_total_usd'] = sum(base_bounties.filter(network='mainnet').values_list('_val_usd_db', flat=True)) context['max_bounty_history'] = float(context['universe_total_usd']) * .7 context['bounty_abandonment_rate'] = '9.5%' context['bounty_average_turnaround'] = '2.1 Weeks' context['hourly_rate_distribution'] = '$15 - $120' context['bounty_claimed_completion_rate'] = '82%' context['bounty_median_pickup_time'] = '2.25' return context
def show_week_date(request, year, month, day): naive = timezone.datetime(int(year), int(month), int(day)) t = pytz.timezone("Europe/Warsaw").localize(naive, is_dst=None) return show_week(request, t)
def test_humanize_relative_date(self): test_cases = [ (timezone.datetime(2021, 1, 1), timezone.datetime(2022, 1, 1), '1 year ago'), (timezone.datetime(2021, 1, 1), timezone.datetime(2022, 12, 31), '1 year ago'), (timezone.datetime(2021, 1, 1), timezone.datetime(2023, 1, 1), '2 years ago'), (timezone.datetime(2021, 1, 1), timezone.datetime(2023, 12, 31), '2 years ago'), (timezone.datetime(2021, 1, 1), timezone.datetime(2021, 12, 31), '11 months ago'), (timezone.datetime(2021, 1, 1), timezone.datetime(2021, 2, 1), '1 month ago'), (timezone.datetime(2021, 1, 1), timezone.datetime(2021, 1, 31), '4 weeks ago'), (timezone.datetime(2021, 1, 1), timezone.datetime(2021, 1, 14), '1 week ago'), (timezone.datetime(2021, 1, 1), timezone.datetime(2021, 1, 8), '1 week ago'), (timezone.datetime(2021, 1, 1), timezone.datetime(2021, 1, 7), 'Friday'), (timezone.datetime(2021, 1, 1), timezone.datetime(2021, 1, 7, 23, 59), 'Friday'), (timezone.datetime(2021, 1, 1), timezone.datetime(2021, 1, 3), 'Friday'), (timezone.datetime(2021, 1, 1), timezone.datetime(2021, 1, 2), 'Yesterday'), (timezone.datetime(2021, 1, 1), timezone.datetime(2021, 1, 2, 23, 59), 'Yesterday'), (timezone.datetime(2021, 1, 1), timezone.datetime(2021, 1, 1), 'Today'), ] for test_case in test_cases: result = humanize_relative_date(test_case[0], test_case[1]) self.assertEqual(test_case[2], result)
'However the projects demo fair will be held in the morning from 10:30 AM to 1 PM.' # (OPTIONAL) Hackathon live page # HACKATHON_LIVE_PAGE = 'https://gerard.space/live' # (OPTIONAL) Regex to automatically match organizers emails and set them as organizers when signing up REGEX_HACKATHON_ORGANIZER_EMAIL = '^.*@gerard\.space$' # (OPTIONAL) Sends 500 errors to email whilst in production mode. HACKATHON_DEV_EMAILS = [] # Reimbursement configuration REIMBURSEMENT_ENABLED = True CURRENCY = '$' REIMBURSEMENT_EXPIRY_DAYS = 5 REIMBURSEMENT_REQUIREMENTS = 'You have to submit a project and demo it during the event in order to get reimbursed' REIMBURSEMENT_DEADLINE = timezone.datetime( 2018, 2, 24, 3, 14, tzinfo=timezone.pytz.timezone(TIME_ZONE)) # (OPTIONAL) Max team members. Defaults to 4 TEAMS_ENABLED = True HACKATHON_MAX_TEAMMATES = 4 # (OPTIONAL) Code of conduct link # CODE_CONDUCT_LINK = "https://pages.hackcu.org/code_conduct/" # (OPTIONAL) Slack credentials # Highly recommended to create a separate user account to extract the token from SLACK = { 'team': os.environ.get('SL_TEAM', 'test'), # Get it here: https://api.slack.com/custom-integrations/legacy-tokens 'token': os.environ.get('SL_TOKEN', None) }
class ExaminationGradeUpdateTestCase(CommonAPITestCase): @classmethod def setUpTestData(cls): cls.academic_calendar = AcademicYearCalendarFactory() cls.corigente_event = SchoolEventFactory(event_type=SchoolEvent.EventTypes.CORIGENTE, academic_year_calendar=cls.academic_calendar, starts_at=datetime.date(2020, 8, 20), ends_at=datetime.date(2020, 8, 27)) cls.diferente_event = SchoolEventFactory(event_type=SchoolEvent.EventTypes.DIFERENTE, academic_year_calendar=cls.academic_calendar, starts_at=datetime.date(2020, 9, 1), ends_at=datetime.date(2020, 9, 8)) cls.school_unit = RegisteredSchoolUnitFactory() cls.school_stats = SchoolUnitStatsFactory(school_unit=cls.school_unit) cls.teacher = UserProfileFactory(user_role=UserProfile.UserRoles.TEACHER, school_unit=cls.school_unit) cls.study_class = StudyClassFactory(school_unit=cls.school_unit, class_grade='IX', class_grade_arabic=9) cls.subject = SubjectFactory() ProgramSubjectThroughFactory(academic_program=cls.study_class.academic_program, class_grade='IX', subject=cls.subject, weekly_hours_count=3) cls.teacher_class_through = TeacherClassThroughFactory( study_class=cls.study_class, teacher=cls.teacher, subject=cls.subject ) cls.student = UserProfileFactory(user_role=UserProfile.UserRoles.STUDENT, student_in_class=cls.study_class) cls.catalog = StudentCatalogPerSubjectFactory( subject=cls.subject, teacher=cls.teacher, student=cls.student, study_class=cls.study_class, is_enrolled=True ) cls.catalog_per_year = StudentCatalogPerYearFactory( student=cls.student, study_class=cls.study_class ) def setUp(self): self.catalog.refresh_from_db() self.data = { 'grade1': 8, 'grade2': 8, 'taken_at': date(2020, 8, 21) } def create_2nd_exam_grade(self, examination_type=ExaminationGrade.ExaminationTypes.WRITTEN): return ExaminationGradeFactory( catalog_per_subject=self.catalog, student=self.catalog.student, examination_type=examination_type, taken_at=datetime.date(2020, 8, 22)) def create_difference_grade(self, examination_type=ExaminationGrade.ExaminationTypes.WRITTEN): return ExaminationGradeFactory( catalog_per_subject=self.catalog, student=self.catalog.student, examination_type=examination_type, taken_at=datetime.date(2020, 9, 2), grade_type=ExaminationGrade.GradeTypes.DIFFERENCE) @staticmethod def build_url(grade_id): return reverse('catalogs:examination-grade-detail', kwargs={'id': grade_id}) def test_examination_grade_update_unauthenticated(self): response = self.client.put(self.build_url(self.create_2nd_exam_grade().id), self.data) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) @data( UserProfile.UserRoles.ADMINISTRATOR, UserProfile.UserRoles.PRINCIPAL, UserProfile.UserRoles.STUDENT, UserProfile.UserRoles.PARENT ) def test_examination_grade_update_wrong_user_type(self, user_role): user = UserProfileFactory( user_role=user_role, school_unit=self.school_unit if user_role != UserProfile.UserRoles.ADMINISTRATOR else None ) self.client.login(username=user.username, password='******') response = self.client.put(self.build_url(self.create_2nd_exam_grade().id), self.data) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_examination_grade_update_catalog_does_not_exist(self): self.client.login(username=self.teacher.username, password='******') response = self.client.put(self.build_url(0), self.data) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) def test_examination_grade_update_teacher_not_assigned(self): self.client.login(username=self.teacher.username, password='******') self.catalog.teacher = UserProfileFactory(user_role=UserProfile.UserRoles.TEACHER) self.catalog.save() response = self.client.put(self.build_url(self.create_2nd_exam_grade().id), self.data) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) @data( datetime.datetime(2020, 8, 22, 8, 59, 59), datetime.datetime(2020, 8, 21, 22, 59) ) @patch('django.utils.timezone.now', return_value=timezone.datetime(2020, 8, 22, 12, 0, 0).replace(tzinfo=utc)) def test_examination_grade_update_grade_more_than_two_hours_in_the_past(self, created_at, mocked_method): self.client.login(username=self.teacher.username, password='******') grade = self.create_2nd_exam_grade() grade.created = created_at.replace(tzinfo=utc) grade.save() response = self.client.put(self.build_url(grade.id), self.data) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.data, {'message': 'Cannot update a grade that was created more than 2 hours ago.'}) @patch('django.utils.timezone.now', return_value=timezone.datetime(2020, 8, 30).replace(tzinfo=utc)) def test_examination_grade_update_outside_event(self, mocked_method): self.client.login(username=self.teacher.username, password='******') response = self.client.put(self.build_url(self.create_2nd_exam_grade().id), self.data) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.data, {'message': 'Cannot update grades at this time.'}) @patch('django.utils.timezone.now', return_value=timezone.datetime(2020, 8, 22).replace(tzinfo=utc)) def test_examination_grade_update_grade_in_the_future(self, mocked_method): self.client.login(username=self.teacher.username, password='******') self.data['taken_at'] = date(2020, 8, 23) response = self.client.put(self.build_url(self.create_2nd_exam_grade().id), self.data) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.data, {'taken_at': ["Can't set grade dates in the future."]}) @data( (11, ['Grade must be between 1 and 10.']), (0, ['Grade must be between 1 and 10.']), (-1, ['Ensure this value is greater than or equal to 0.']), (None, ['This field may not be null.']), ('', ['A valid integer is required.']), ) @unpack @patch('django.utils.timezone.now', return_value=timezone.datetime(2020, 8, 22).replace(tzinfo=utc)) def test_examination_grade_update_grade_validation(self, grade, expected_response, mocked_method): self.client.login(username=self.teacher.username, password='******') for grade_field in ['grade1', 'grade2']: request_data = copy(self.data) request_data[grade_field] = grade response = self.client.put(self.build_url(self.create_2nd_exam_grade().id), request_data) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.data[grade_field], expected_response) @patch('django.utils.timezone.now', return_value=timezone.datetime(2020, 8, 22).replace(tzinfo=utc)) def test_examination_grade_update_2nd_exam_grade_success(self, mocked_method): self.client.login(username=self.teacher.username, password='******') for catalog in [self.catalog, self.catalog_per_year]: catalog.avg_annual = 5 catalog.save() self.create_2nd_exam_grade() grade = self.create_2nd_exam_grade(examination_type=ExaminationGrade.ExaminationTypes.ORAL) response = self.client.put(self.build_url(grade.id), self.data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.check_data(response, grade) self.refresh_objects_from_db([self.catalog, self.catalog_per_year, self.study_class, self.study_class.academic_program, self.school_stats, self.teacher, self.teacher.school_unit]) for catalog in [self.catalog, self.catalog_per_year]: self.assertEqual(catalog.avg_annual, 5) self.assertEqual(catalog.avg_final, 9) self.assertEqual(self.catalog.avg_after_2nd_examination, 9) for obj in [self.study_class, self.study_class.academic_program, self.school_stats]: self.assertEqual(obj.avg_annual, 9) @patch('django.utils.timezone.now', return_value=timezone.datetime(2020, 9, 3).replace(tzinfo=utc)) def test_examination_grade_update_difference_grade_success(self, mocked_method): self.client.login(username=self.teacher.username, password='******') self.create_difference_grade() grade = self.create_difference_grade(examination_type=ExaminationGrade.ExaminationTypes.ORAL) self.data['taken_at'] = date(2020, 9, 3) response = self.client.put(self.build_url(grade.id), self.data) self.assertEqual(response.status_code, status.HTTP_200_OK) self.check_data(response, grade) self.refresh_objects_from_db([self.catalog, self.catalog_per_year, self.study_class, self.study_class.academic_program, self.school_stats, self.teacher, self.teacher.school_unit]) for catalog in [self.catalog, self.catalog_per_year]: self.assertEqual(catalog.avg_annual, 9) self.assertEqual(catalog.avg_final, 9) for obj in [self.study_class, self.study_class.academic_program, self.school_stats]: self.assertEqual(obj.avg_annual, 9) def check_data(self, response, grade): catalog_expected_fields = [ 'id', 'student', 'avg_sem1', 'avg_sem2', 'avg_annual', 'avg_after_2nd_examination', 'avg_limit', 'abs_count_sem1', 'abs_count_sem2', 'abs_count_annual', 'founded_abs_count_sem1', 'founded_abs_count_sem2', 'founded_abs_count_annual', 'unfounded_abs_count_sem1', 'unfounded_abs_count_sem2', 'unfounded_abs_count_annual', 'grades_sem1', 'grades_sem2', 'abs_sem1', 'abs_sem2', 'second_examination_grades', 'difference_grades_sem1', 'difference_grades_sem2', 'wants_thesis', 'is_exempted', 'third_of_hours_count_sem1', 'third_of_hours_count_sem2', 'third_of_hours_count_annual', 'is_coordination_subject' ] examination_grade_fields = ['id', 'examination_type', 'taken_at', 'grade1', 'grade2', 'created'] self.assertCountEqual(response.data.keys(), catalog_expected_fields) for examination_data in response.data['second_examination_grades'] + response.data['difference_grades_sem1'] + response.data['difference_grades_sem2']: self.assertCountEqual(examination_data.keys(), examination_grade_fields) grade.refresh_from_db() self.assertEqual(grade.grade1, self.data['grade1']) self.assertEqual(grade.grade2, self.data['grade2']) self.assertEqual(grade.taken_at.strftime(settings.DATE_FORMAT), self.data['taken_at']) self.teacher.refresh_from_db() self.assertEqual(self.teacher.last_change_in_catalog, timezone.now()) self.assertEqual(self.teacher.school_unit.last_change_in_catalog, timezone.now())
def substitutions( request: HttpRequest, year: Optional[int] = None, month: Optional[int] = None, day: Optional[int] = None, is_print: bool = False, ) -> HttpResponse: """View all substitutions on a spcified day.""" context = {} if day: wanted_day = timezone.datetime(year=year, month=month, day=day).date() wanted_day = TimePeriod.get_next_relevant_day(wanted_day) else: wanted_day = TimePeriod.get_next_relevant_day(timezone.now().date(), datetime.now().time()) day_number = get_site_preferences( )["chronos__substitutions_print_number_of_days"] day_contexts = {} if is_print: next_day = wanted_day for i in range(day_number): day_contexts[next_day] = {"day": next_day} next_day = TimePeriod.get_next_relevant_day(next_day + timedelta(days=1)) else: day_contexts = {wanted_day: {"day": wanted_day}} for day in day_contexts: subs = build_substitutions_list(day) day_contexts[day]["substitutions"] = subs day_contexts[day]["announcements"] = ( Announcement.for_timetables().on_date(day).filter( show_in_timetables=True)) if get_site_preferences()["chronos__substitutions_show_header_box"]: subs = LessonSubstitution.objects.on_day(day).order_by( "lesson_period__lesson__groups", "lesson_period__period") absences = Absence.objects.on_day(day) day_contexts[day]["absent_teachers"] = absences.absent_teachers() day_contexts[day]["absent_groups"] = absences.absent_groups() day_contexts[day]["affected_teachers"] = subs.affected_teachers() affected_groups = subs.affected_groups() if get_site_preferences( )["chronos__affected_groups_parent_groups"]: groups_with_parent_groups = affected_groups.filter( parent_groups__isnull=False) groups_without_parent_groups = affected_groups.filter( parent_groups__isnull=True) affected_groups = Group.objects.filter( Q(child_groups__pk__in=groups_with_parent_groups. values_list("pk", flat=True)) | Q(pk__in=groups_without_parent_groups.values_list( "pk", flat=True))).distinct() day_contexts[day]["affected_groups"] = affected_groups if not is_print: context = day_contexts[wanted_day] context["datepicker"] = { "date": date_unix(wanted_day), "dest": reverse("substitutions"), } context["url_prev"], context[ "url_next"] = TimePeriod.get_prev_next_by_day( wanted_day, "substitutions_by_date") return render(request, "chronos/substitutions.html", context) else: context["days"] = day_contexts return render_pdf(request, "chronos/substitutions_print.html", context)
def test_search(self): """ Objects with status "Draft" should not be within search results. """ RichTextPage.objects.all().delete() published = {"status": CONTENT_STATUS_PUBLISHED} first = RichTextPage.objects.create(title="test page", status=CONTENT_STATUS_DRAFT).id second = RichTextPage.objects.create(title="test another test page", **published).id # Draft shouldn't be a result. results = RichTextPage.objects.search("test") self.assertEqual(len(results), 1) RichTextPage.objects.filter(id=first).update(**published) results = RichTextPage.objects.search("test") self.assertEqual(len(results), 2) # Either word. results = RichTextPage.objects.search("another test") self.assertEqual(len(results), 2) # Must include first word. results = RichTextPage.objects.search("+another test") self.assertEqual(len(results), 1) # Mustn't include first word. results = RichTextPage.objects.search("-another test") self.assertEqual(len(results), 1) if results: self.assertEqual(results[0].id, first) # Exact phrase. results = RichTextPage.objects.search('"another test"') self.assertEqual(len(results), 1) if results: self.assertEqual(results[0].id, second) # Test ordering without age scaling. settings.SEARCH_AGE_SCALE_FACTOR = 0 RichTextPage.objects.filter(id=first).update(publish_date=now() - timedelta(days=3)) RichTextPage.objects.filter(id=second).update( publish_date=datetime(2016, 1, 1, tzinfo=pytz.utc)) results = RichTextPage.objects.search("test") self.assertEqual(len(results), 2) if results: self.assertEqual(results[0].id, second) # Test ordering with age scaling. settings.SEARCH_AGE_SCALE_FACTOR = 1.5 results = RichTextPage.objects.search("test") self.assertEqual(len(results), 2) if results: # `first` should now be ranked higher. self.assertEqual(results[0].id, first) # Test results that have a publish date in the future future = RichTextPage.objects.create( title="test page to be published in the future", publish_date=now() + timedelta(days=10), **published).id results = RichTextPage.objects.search("test", for_user=self._username) self.assertEqual(len(results), 3) if results: self.assertEqual(results[0].id, future) # Test the actual search view. response = self.client.get(reverse("search") + "?q=test") self.assertEqual(response.status_code, 200)
def __init__(self, source): self.source = os.path.join(DATA_DIR, 'test.txt') self.file_path = os.path.join(DATA_DIR, source) self.size = 254 self.last_modified = timezone.make_aware(timezone.datetime( 1989, 8, 25))
class GradeDeleteTestCase(CommonAPITestCase): @classmethod def setUpTestData(cls): cls.academic_calendar = AcademicYearCalendarFactory() cls.school_unit = RegisteredSchoolUnitFactory() cls.school_stats = SchoolUnitStatsFactory(school_unit=cls.school_unit) cls.teacher = UserProfileFactory( user_role=UserProfile.UserRoles.TEACHER, school_unit=cls.school_unit) cls.study_class = StudyClassFactory(school_unit=cls.school_unit) cls.subject = SubjectFactory() cls.teacher_class_through = TeacherClassThroughFactory( study_class=cls.study_class, teacher=cls.teacher, subject=cls.subject) ProgramSubjectThroughFactory( academic_program=cls.study_class.academic_program, subject=cls.subject, weekly_hours_count=1, class_grade=cls.study_class.class_grade, class_grade_arabic=cls.study_class.class_grade_arabic) cls.student = UserProfileFactory( user_role=UserProfile.UserRoles.STUDENT, student_in_class=cls.study_class) cls.catalog = StudentCatalogPerSubjectFactory( subject=cls.subject, teacher=cls.teacher, student=cls.student, study_class=cls.study_class, academic_year=2020, is_enrolled=True) cls.catalog_per_year = StudentCatalogPerYearFactory( student=cls.student, study_class=cls.study_class) def setUp(self): self.catalog.refresh_from_db() def create_grade(self): return SubjectGradeFactory(catalog_per_subject=self.catalog, student=self.catalog.student, taken_at=datetime.date(2020, 4, 4), semester=2) @staticmethod def build_url(grade_id): return reverse('catalogs:grade-detail', kwargs={'id': grade_id}) def test_grade_delete_unauthenticated(self): response = self.client.delete(self.build_url(self.create_grade().id)) self.assertEqual(response.status_code, status.HTTP_401_UNAUTHORIZED) @data(UserProfile.UserRoles.ADMINISTRATOR, UserProfile.UserRoles.PRINCIPAL, UserProfile.UserRoles.STUDENT, UserProfile.UserRoles.PARENT) def test_grade_delete_wrong_user_type(self, user_role): user = UserProfileFactory( user_role=user_role, school_unit=self.school_unit if user_role != UserProfile.UserRoles.ADMINISTRATOR else None) self.client.login(username=user.username, password='******') response = self.client.delete(self.build_url(self.create_grade().id)) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) def test_grade_delete_grade_does_not_exist(self): self.client.login(username=self.teacher.username, password='******') response = self.client.delete(self.build_url(0)) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) def test_grade_delete_teacher_not_assigned(self): self.client.login(username=self.teacher.username, password='******') self.catalog.teacher = UserProfileFactory( user_role=UserProfile.UserRoles.TEACHER) self.catalog.save() response = self.client.delete(self.build_url(self.create_grade().id)) self.assertEqual(response.status_code, status.HTTP_404_NOT_FOUND) def test_grade_delete_coordination_subject(self): self.client.login(username=self.teacher.username, password='******') self.catalog.is_coordination_subject = True self.catalog.save() response = self.client.delete(self.build_url(self.create_grade().id)) self.assertEqual(response.status_code, status.HTTP_400_BAD_REQUEST) self.assertEqual(response.data['message'], "Can't delete coordination subject grade.") @patch('django.utils.timezone.now', return_value=timezone.datetime(2020, 4, 4, 12, 0, 0).replace(tzinfo=utc)) def test_grade_delete_success(self, mocked_method): self.client.login(username=self.teacher.username, password='******') grade = self.create_grade() response = self.client.delete(self.build_url(grade.id)) self.assertEqual(response.status_code, status.HTTP_200_OK) self.assertFalse(SubjectGrade.objects.filter(id=grade.id).exists()) catalog_expected_fields = [ 'id', 'student', 'avg_sem1', 'avg_sem2', 'avg_annual', 'avg_after_2nd_examination', 'avg_limit', 'abs_count_sem1', 'abs_count_sem2', 'abs_count_annual', 'founded_abs_count_sem1', 'founded_abs_count_sem2', 'founded_abs_count_annual', 'unfounded_abs_count_sem1', 'unfounded_abs_count_sem2', 'unfounded_abs_count_annual', 'grades_sem1', 'grades_sem2', 'abs_sem1', 'abs_sem2', 'second_examination_grades', 'difference_grades_sem1', 'difference_grades_sem2', 'wants_thesis', 'is_exempted', 'third_of_hours_count_sem1', 'third_of_hours_count_sem2', 'third_of_hours_count_annual', 'is_coordination_subject' ] grade_fields = ['id', 'grade', 'taken_at', 'grade_type', 'created'] self.assertCountEqual(response.data.keys(), catalog_expected_fields) for grade_data in response.data['grades_sem1'] + response.data[ 'grades_sem2']: self.assertCountEqual(grade_data.keys(), grade_fields) self.teacher.refresh_from_db() self.assertEqual( self.teacher.last_change_in_catalog, timezone.datetime(2020, 4, 4, 12, 0, 0).replace(tzinfo=utc)) self.assertEqual( self.teacher.school_unit.last_change_in_catalog, timezone.datetime(2020, 4, 4, 12, 0, 0).replace(tzinfo=utc)) @patch('django.utils.timezone.now', return_value=timezone.datetime(2019, 11, 10).replace(tzinfo=utc)) def test_grade_delete_secondary_school_averages(self, mocked_method): # This is for a subject with weekly hours count = 1 and no thesis (1st semester) self.client.login(username=self.teacher.username, password='******') SubjectGradeFactory(student=self.student, catalog_per_subject=self.catalog, semester=1, grade=8) grade1 = SubjectGradeFactory(student=self.student, catalog_per_subject=self.catalog, semester=1, grade=8) grade2 = SubjectGradeFactory(student=self.student, catalog_per_subject=self.catalog, semester=1, grade=10) self.catalog.avg_sem1 = 9 self.catalog.save() response = self.client.delete(self.build_url(grade2.id)) self.assertEqual(response.status_code, status.HTTP_200_OK) self.refresh_objects_from_db([ self.catalog, self.catalog_per_year, self.study_class, self.school_stats ]) for obj in [ self.catalog, self.catalog_per_year, self.study_class, self.school_stats ]: self.assertEqual(obj.avg_sem1, 8) self.assertIsNone(obj.avg_sem2) self.assertIsNone(obj.avg_annual) self.assertIsNone(self.catalog.avg_final) self.assertIsNone(self.catalog_per_year.avg_final) response = self.client.delete(self.build_url(grade1.id)) self.assertEqual(response.status_code, status.HTTP_200_OK) self.refresh_objects_from_db([ self.catalog, self.catalog_per_year, self.study_class, self.school_stats ]) for obj in [ self.catalog, self.catalog_per_year, self.study_class, self.school_stats ]: self.assertIsNone(obj.avg_sem1) self.assertIsNone(obj.avg_sem2) self.assertIsNone(obj.avg_annual) self.assertIsNone(self.catalog.avg_final) self.assertIsNone(self.catalog_per_year.avg_final) @patch('django.utils.timezone.now', return_value=timezone.datetime(2020, 3, 3).replace(tzinfo=utc)) def test_grade_delete_highschool_school_averages(self, mocked_method): # This is for an optional subject with weekly hours count = 3 and with thesis (2nd semester) self.client.login(username=self.teacher.username, password='******') self.study_class.class_grade = 'IX' self.study_class.class_grade_arabic = 9 self.study_class.save() ProgramSubjectThroughFactory( academic_program=self.study_class.academic_program, subject=self.subject, weekly_hours_count=3) for i in range(3): SubjectGradeFactory(student=self.student, catalog_per_subject=self.catalog, semester=2, grade=9) grade1 = SubjectGradeFactory(student=self.student, catalog_per_subject=self.catalog, semester=2, grade=6, grade_type=SubjectGrade.GradeTypes.THESIS) grade2 = SubjectGradeFactory(student=self.student, catalog_per_subject=self.catalog, semester=2, grade=10) SubjectGradeFactory(student=self.student, catalog_per_subject=self.catalog, semester=2, grade=10) self.catalog.avg_sem1 = 9 self.catalog.avg_sem2 = 9 self.catalog.avg_annual = 9 self.catalog.avg_final = 9 self.catalog.wants_thesis = True self.catalog.save() response = self.client.delete(self.build_url(grade2.id)) self.assertEqual(response.status_code, status.HTTP_200_OK) self.refresh_objects_from_db([ self.catalog, self.catalog_per_year, self.study_class, self.study_class.academic_program, self.school_stats ]) for obj in [ self.catalog, self.catalog_per_year, self.study_class, self.study_class.academic_program, self.school_stats ]: self.assertEqual(obj.avg_sem1, 9) self.assertEqual(obj.avg_sem2, 8) self.assertEqual(obj.avg_annual, 8.5) self.assertEqual(self.catalog.avg_final, 8.5) self.assertEqual(self.catalog_per_year.avg_final, 8.5) response = self.client.delete(self.build_url(grade1.id)) self.assertEqual(response.status_code, status.HTTP_200_OK) self.catalog.refresh_from_db() self.assertEqual(self.catalog.avg_sem1, 9) self.assertIsNone(self.catalog.avg_sem2) self.assertIsNone(self.catalog.avg_annual) self.assertIsNone(self.catalog.avg_final) self.refresh_objects_from_db([ self.catalog, self.catalog_per_year, self.study_class, self.study_class.academic_program, self.school_stats ]) for obj in [ self.catalog, self.catalog_per_year, self.study_class, self.study_class.academic_program, self.school_stats ]: self.assertEqual(obj.avg_sem1, 9) self.assertIsNone(obj.avg_sem2) self.assertIsNone(obj.avg_annual) self.assertIsNone(self.catalog.avg_final) self.assertIsNone(self.catalog_per_year.avg_final)
def get(self, request): # noqa: C901 capabilities = dsmr_backend.services.backend.get_capabilities() frontend_settings = FrontendSettings.get_solo() now = timezone.now().strftime( formats.get_format('DSMR_STRFTIME_DATE_FORMAT')) given_date = request.GET.get('date', now) selected_datetime = timezone.make_aware( timezone.datetime.strptime( given_date, formats.get_format('DSMR_STRFTIME_DATE_FORMAT'))) selected_level = request.GET.get('level', 'days') data = defaultdict(list) response = { 'merge_electricity_tariffs': frontend_settings.merge_electricity_tariffs, } x_format_callback = None FIELDS = ('electricity1', 'electricity2', 'electricity1_returned', 'electricity2_returned', 'electricity_merged', 'electricity_returned_merged', 'gas') # Zoom to hourly data. if selected_level == 'days': hours_in_day = dsmr_backend.services.backend.hours_in_day( day=selected_datetime.date()) source_data = HourStatistics.objects.filter( hour_start__gte=selected_datetime, hour_start__lte=selected_datetime + timezone.timedelta(hours=hours_in_day)).order_by('hour_start') x_format = 'DSMR_GRAPH_SHORT_TIME_FORMAT' x_axis = 'hour_start' x_format_callback = timezone.localtime # Zoom to daily data. elif selected_level == 'months': start_of_month = timezone.datetime(year=selected_datetime.year, month=selected_datetime.month, day=1) end_of_month = timezone.datetime.combine( start_of_month + relativedelta(months=1), time.min) source_data = DayStatistics.objects.filter( day__gte=start_of_month, day__lt=end_of_month).order_by('day') x_format = 'DSMR_GRAPH_SHORT_DATE_FORMAT' x_axis = 'day' # Zoom to monthly data. elif selected_level == 'years': source_data = [] start_of_year = timezone.datetime(year=selected_datetime.year, month=1, day=1) for increment in range(0, 12): current_month = start_of_year + relativedelta(months=increment) current_month_stats, _ = dsmr_stats.services.month_statistics( current_month.date()) current_month_stats['month'] = current_month.date() source_data.append(current_month_stats) x_format = 'DSMR_DATEPICKER_MONTH' x_axis = 'month' for current_item in source_data: try: x_value = getattr(current_item, x_axis) except AttributeError: x_value = current_item[x_axis] if x_format_callback: x_value = x_format_callback(x_value) data['x'].append(formats.date_format(x_value, x_format)) for current_field in FIELDS: try: y_value = getattr(current_item, current_field) or 0 except AttributeError: y_value = current_item[current_field] or 0 data[current_field].append(float(y_value)) if frontend_settings.merge_electricity_tariffs: response['electricity'] = { 'x': data['x'], 'electricity_merged': data['electricity_merged'], } else: response['electricity'] = { 'x': data['x'], 'electricity1': data['electricity1'], 'electricity2': data['electricity2'], } if capabilities['electricity_returned']: if frontend_settings.merge_electricity_tariffs: response['electricity_returned'] = { 'x': data['x'], 'electricity_returned_merged': data['electricity_returned_merged'], } else: response['electricity_returned'] = { 'x': data['x'], 'electricity1_returned': data['electricity1_returned'], 'electricity2_returned': data['electricity2_returned'], } if capabilities['gas']: response['gas'] = { 'x': data['x'], 'gas': data['gas'], } return JsonResponse(response)
def setUp(self): appetizer_time = timezone.datetime( date.today().year, date.today().month, date.today().day, 17, ), main_course_time = timezone.datetime( date.today().year, date.today().month, date.today().day, 18, 30, ), dessert_time = timezone.datetime( date.today().year, date.today().month, date.today().day, 20, 30, ) afterparty_time = timezone.datetime( date.today().year, date.today().month, date.today().day, 20, 30, ) self.appetizer = Course.objects.get(name="a") self.main_menu = Course.objects.get(name="m") self.dessert = Course.objects.get(name="d") advisor = Advisor( name="TestAdvisorName", phone="0123000001", email="testuser1@%s" % EMAIL_DOMAIN ) advisor.full_clean() advisor.save() self.event = Event( advisor=advisor, name="TestEventName", semester="TestEventSemester", description_de="TestEventDescriptionDE", description_en="TestEventDescriptionEN", date="%s" % (date.today() + timezone.timedelta(weeks=4)), end_registration="%s" % (date.today() + timezone.timedelta(weeks=3)), appetizer_time="%s" % appetizer_time, main_course_time="%s" % main_course_time, dessert_time="%s" % dessert_time, afterparty_time="%s" % afterparty_time, afterparty_location="TestAfterpartyLocation", active=True, ) self.event.full_clean() self.event.save() team1 = Team( event=self.event, name="TestTeam1Name", street="Mittelstraße 129", city="Mannheim", postal_code="68169", doorbell="TestTeam1Doorbell", participant_1_firstname="TestTeam1Participant1Firstname", participant_1_lastname="TestTeam1Participant1Lastname", participant_1_email="testuser2@%s" % EMAIL_DOMAIN, participant_1_phone="0123000002", participant_2_firstname="TestTeam1Participant2Firstname", participant_2_lastname="TestTeam1Participant2Lastname", participant_2_email="testuser3@%s" % EMAIL_DOMAIN, participant_2_phone="0123000003", allergies="TestTeam1Allergies", language="de", ) team1.full_clean() team1.save() team1.like.add(self.appetizer) team2 = Team( event=self.event, name="TestTeam2Name", street="Am Meßplatz 1", city="Mannheim", postal_code="68169", doorbell="TestTeam2Doorbell", participant_1_firstname="TestTeam2Participant1Firstname", participant_1_lastname="TestTeam2Participant1Lastname", participant_1_email="testuser4@%s" % EMAIL_DOMAIN, participant_1_phone="0123000004", participant_2_firstname="TestTeam2Participant2Firstname", participant_2_lastname="TestTeam2Participant2Lastname", participant_2_email="testuser5@%s" % EMAIL_DOMAIN, participant_2_phone="0123000005", allergies="TestTeam2Allergies", language="de", ) team2.full_clean() team2.save() team2.like.add(self.appetizer) team2.like.add(self.main_menu) team3 = Team( event=self.event, name="TestTeam3Name", street="Mozartstr. 9", city="Mannheim", postal_code="68161", doorbell="TestTeam3Doorbell", participant_1_firstname="TestTeam3Participant1Firstname", participant_1_lastname="TestTeam3Participant1Lastname", participant_1_email="testuser6@%s" % EMAIL_DOMAIN, participant_1_phone="0123000006", participant_2_firstname="TestTeam3Participant2Firstname", participant_2_lastname="TestTeam3Participant2Lastname", participant_2_email="testuser7@%s" % EMAIL_DOMAIN, participant_2_phone="0123000007", allergies="TestTeam3Allergies", language="de", ) team3.full_clean() team3.save() team3.like.add(self.appetizer) team3.like.add(self.dessert) team4 = Team( event=self.event, name="TestTeam4Name", street="Böckstraße 16", city="Mannheim", postal_code="68159", doorbell="TestTeam4Doorbell", participant_1_firstname="TestTeam4Participant1Firstname", participant_1_lastname="TestTeam4Participant1Lastname", participant_1_email="testuser8@%s" % EMAIL_DOMAIN, participant_1_phone="0123000008", participant_2_firstname="TestTeam4Participant2Firstname", participant_2_lastname="TestTeam4Participant2Lastname", participant_2_email="testuser9@%s" % EMAIL_DOMAIN, participant_2_phone="0123000009", allergies="TestTeam4Allergies", language="de", ) team4.full_clean() team4.save() team4.like.add(self.appetizer) team4.dislike.add(self.main_menu) team4.dislike.add(self.dessert) team5 = Team( event=self.event, name="TestTeam5Name", street="H7 7", city="Mannheim", postal_code="68161", doorbell="TestTeam5Doorbell", participant_1_firstname="TestTeam5Participant1Firstname", participant_1_lastname="TestTeam5Participant1Lastname", participant_1_email="testuser10@%s" % EMAIL_DOMAIN, participant_1_phone="0123000010", participant_2_firstname="TestTeam5Participant2Firstname", participant_2_lastname="TestTeam5Participant2Lastname", participant_2_email="testuser11@%s" % EMAIL_DOMAIN, participant_2_phone="0123000011", allergies="TestTeam5Allergies", language="de", ) team5.full_clean() team5.save() team5.like.add(self.main_menu) team6 = Team( event=self.event, name="TestTeam6Name", street="T4 5", city="Mannheim", postal_code="68161", doorbell="TestTeam6Doorbell", participant_1_firstname="TestTeam6Participant1Firstname", participant_1_lastname="TestTeam6Participant1Lastname", participant_1_email="testuser12@%s" % EMAIL_DOMAIN, participant_1_phone="0123000012", participant_2_firstname="TestTeam6Participant2Firstname", participant_2_lastname="TestTeam6Participant2Lastname", participant_2_email="testuser13@%s" % EMAIL_DOMAIN, participant_2_phone="0123000013", allergies="TestTeam6Allergies", language="de", ) team6.full_clean() team6.save() team6.like.add(self.main_menu) team6.like.add(self.appetizer) team7 = Team( event=self.event, name="TestTeam7Name", street="B7 9", city="Mannheim", postal_code="68161", doorbell="TestTeam7Doorbell", participant_1_firstname="TestTeam7Participant1Firstname", participant_1_lastname="TestTeam7Participant1Lastname", participant_1_email="testuser14@%s" % EMAIL_DOMAIN, participant_1_phone="0123000014", participant_2_firstname="TestTeam7Participant2Firstname", participant_2_lastname="TestTeam7Participant2Lastname", participant_2_email="testuser15@%s" % EMAIL_DOMAIN, participant_2_phone="0123000015", allergies="TestTeam7Allergies", language="de", ) team7.full_clean() team7.save() team7.like.add(self.main_menu) team7.like.add(self.dessert) team8 = Team( event=self.event, name="TestTeam8Name", street="N5 2", city="Mannheim", postal_code="68161", doorbell="TestTeam8Doorbell", participant_1_firstname="TestTeam8Participant1Firstname", participant_1_lastname="TestTeam8Participant1Lastname", participant_1_email="testuser16@%s" % EMAIL_DOMAIN, participant_1_phone="0123000016", participant_2_firstname="TestTeam8Participant2Firstname", participant_2_lastname="TestTeam8Participant2Lastname", participant_2_email="testuser17@%s" % EMAIL_DOMAIN, participant_2_phone="0123000017", allergies="TestTeam8Allergies", language="de", ) team8.full_clean() team8.save() team8.like.add(self.main_menu) team8.dislike.add(self.appetizer) team8.dislike.add(self.dessert) team9 = Team( event=self.event, name="TestTeam9Name", street="Rathenaustraße 19", city="Mannheim", postal_code="68165", doorbell="TestTeam9Doorbell", participant_1_firstname="TestTeam9Participant1Firstname", participant_1_lastname="TestTeam9Participant1Lastname", participant_1_email="testuser18@%s" % EMAIL_DOMAIN, participant_1_phone="0123000018", participant_2_firstname="TestTeam9Participant2Firstname", participant_2_lastname="TestTeam9Participant2Lastname", participant_2_email="testuser19@%s" % EMAIL_DOMAIN, participant_2_phone="0123000019", allergies="TestTeam9Allergies", language="de", ) team9.full_clean() team9.save() team9.like.add(self.dessert) team10 = Team( event=self.event, name="TestTeam10Name", street="Spinozastraße 11", city="Mannheim", postal_code="68165", doorbell="TestTeam10Doorbell", participant_1_firstname="TestTeam10Participant1Firstname", participant_1_lastname="TestTeam10Participant1Lastname", participant_1_email="testuser20@%s" % EMAIL_DOMAIN, participant_1_phone="0123000020", participant_2_firstname="TestTeam10Participant2Firstname", participant_2_lastname="TestTeam10Participant2Lastname", participant_2_email="testuser21@%s" % EMAIL_DOMAIN, participant_2_phone="0123000021", allergies="TestTeam10Allergies", language="de", ) team10.full_clean() team10.save() team10.like.add(self.dessert) team10.like.add(self.appetizer) team11 = Team( event=self.event, name="TestTeam11Name", street="Augartenstr 95", city="Mannheim", postal_code="68169", doorbell="TestTeam11Doorbell", participant_1_firstname="TestTeam11Participant1Firstname", participant_1_lastname="TestTeam11Participant1Lastname", participant_1_email="testuser22@%s" % EMAIL_DOMAIN, participant_1_phone="0123000022", participant_2_firstname="TestTeam11Participant2Firstname", participant_2_lastname="TestTeam11Participant2Lastname", participant_2_email="testuser23@%s" % EMAIL_DOMAIN, participant_2_phone="0123000023", allergies="TestTeam11Allergies", language="de", ) team11.full_clean() team11.save() team11.like.add(self.dessert) team11.like.add(self.main_menu) team12 = Team( event=self.event, name="TestTeam12Name", street="Traubenstraße 14", city="Mannheim", postal_code="68199", doorbell="TestTeam12Doorbell", participant_1_firstname="TestTeam12Participant1Firstname", participant_1_lastname="TestTeam12Participant1Lastname", participant_1_email="testuser24@%s" % EMAIL_DOMAIN, participant_1_phone="0123000024", participant_2_firstname="TestTeam12Participant2Firstname", participant_2_lastname="TestTeam12Participant2Lastname", participant_2_email="testuser25@%s" % EMAIL_DOMAIN, participant_2_phone="0123000025", allergies="TestTeam12Allergies", language="de", ) team12.full_clean() team12.save() team12.like.add(self.dessert) team12.dislike.add(self.appetizer) team12.dislike.add(self.main_menu) self.factory = RequestFactory()
def get_codefund_history_at_date(date, keyword): date = date.replace(tzinfo=None) amount = 0 # July => Feb 2019 # $5,500.00 $4,400.00 $9,000.00 $8,500.00 $7,450.00 $6,150.00 $9,700.00 $6,258.31 if date > timezone.datetime(2018, 7, 23): amount += 5500 if date > timezone.datetime(2018, 8, 23): amount += 4400 if date > timezone.datetime(2018, 9, 23): amount += 9000 if date > timezone.datetime(2018, 10, 23): amount += 8500 if date > timezone.datetime(2018, 11, 23): amount += 7450 if date > timezone.datetime(2018, 12, 23): amount += 6150 if date > timezone.datetime(2019, 1, 9): amount += 9700 if date > timezone.datetime(2019, 2, 9): amount += 11272 if date > timezone.datetime(2019, 3, 9): amount += 18726 if date > timezone.datetime(2019, 4, 9): amount += 35461 if date > timezone.datetime(2019, 5, 9): amount += 41073 if date > timezone.datetime(2019, 6, 9): amount += 38287.22 if date > timezone.datetime(2019, 7, 9): amount += 40269 if date > timezone.datetime(2019, 8, 9): amount += 50871 if date > timezone.datetime(2019, 9, 9): amount += 55000 if date > timezone.datetime(2019, 10, 9): amount += sum(ManualStat.objects.filter(key='codefund_gmv', date__lt=date).values_list('val', flat=True)) return amount