Exemple #1
0
 def test_init_value_error(self):
     with self.assertRaises(ValueError):
         Availability([])
     with self.assertRaises(ValueError):
         Availability([True for i in range(671)])
     with self.assertRaises(ValueError):
         Availability([True for i in range(673)])
Exemple #2
0
def period_avail(period, days, hours, minutes):
    plist = ('daily', 'weekly', 'monthly', 'yearly')
    av = Availability(days, hours, minutes)
    if period in plist and isinstance(period, str):
        return json.dumps(av.service(period=period, out_dict=True))
    else:
        return json.dumps({"error":"period not properly set, must be of : "
                            + str(plist)})
Exemple #3
0
 def test_new_timezone_wt_shift_forward(self):
     new_wt = Availability.new_timezone_wt(c.sunday_0000, c.et_ds, 'UTC')
     self.assertEqual(new_wt, WeeklyTime(0, 4, 0))
     new_wt = Availability.new_timezone_wt(c.tuesday_1715, c.et_no_ds,
                                           'Asia/Tokyo')
     self.assertEqual(new_wt, WeeklyTime(3, 7, 15))
     new_wt = Availability.new_timezone_wt(c.saturday_2345,
                                           c.kathmandu_2017_end,
                                           'Australia/West')
     self.assertEqual(new_wt, WeeklyTime(0, 2, 0))
Exemple #4
0
 def test_new_timezone_wt_shift_backward(self):
     new_wt = Availability.new_timezone_wt(c.sunday_0000, c.et_ds,
                                           'US/Arizona')
     self.assertEqual(new_wt, WeeklyTime(6, 21, 0))
     new_wt = Availability.new_timezone_wt(c.tuesday_1715, c.kabul_2000_1_1,
                                           'US/Samoa')
     self.assertEqual(new_wt, WeeklyTime(2, 1, 45))
     new_wt = Availability.new_timezone_wt(c.thursday_0630, c.chatham_ds,
                                           'Pacific/Midway')
     self.assertEqual(new_wt, WeeklyTime(3, 5, 45))
Exemple #5
0
 def test_from_dict_value_error(self):
     with self.assertRaises(ValueError):
         Availability.from_dict({0: ['00:00', '01:00']})
     with self.assertRaises(ValueError):
         Availability.from_dict({'0': ['00:00']})
     with self.assertRaises(ValueError):
         Availability.from_dict({'0': ['00:00', '00:15', '00:30']})
     with self.assertRaises(ValueError):
         Availability.from_dict({'0': ['00:00', '00:00']})
     with self.assertRaises(ValueError):
         Availability.from_dict({'0': ['00:14', '01:00']})
Exemple #6
0
    def test_new_timezone_availability_utc_et_daylight_saving(self):
        # Shift forward
        user = c.new_user(c.student, {'tz_str': 'US/Eastern'})
        new_avail = user.new_timezone_availability('UTC', c.dt_us_ds)
        avail = Availability.from_dict({'0': [['04:00', '05:30']]})
        self.assertEqual(new_avail, avail)

        # Shift backward
        user = c.new_user(c.student, {'tz_str': 'UTC'})
        new_avail = user.new_timezone_availability('US/Eastern', c.dt_us_ds)
        avail = Availability.from_dict({'6': [['20:00', '21:30']]})
        self.assertEqual(new_avail, avail)
Exemple #7
0
    def test_new_timezone_utc_et_daylight_saving(self):
        # Shift forward
        new_avail = c.free_first_five_avail.new_timezone(
            'US/Eastern', 'UTC', c.dt_us_ds)
        correct_avail = Availability.from_dict({'0': [['04:00', '05:15']]})
        self.assertEqual(new_avail, correct_avail)

        # Shift backward
        new_avail = c.free_first_five_avail.new_timezone(
            'UTC', 'US/Eastern', c.dt_us_ds)
        correct_avail = Availability.from_dict({'6': [['20:00', '21:15']]})
        self.assertEqual(new_avail, correct_avail)
Exemple #8
0
    def test_new_timezone_midway_chatham_daylight_saving(self):
        # Shift forward
        new_avail = c.free_first_six_avail.new_timezone(
            'Pacific/Midway', 'Pacific/Chatham', c.dt_chatham_ds)
        correct_avail = Availability.from_dict({'1': [['00:45', '02:15']]})
        self.assertEqual(new_avail, correct_avail)

        # Shift backward
        new_avail = c.free_first_six_avail.new_timezone(
            'Pacific/Chatham', 'Pacific/Midway', c.dt_chatham_ds)
        correct_avail = Availability.from_dict({
            '5': [['23:15', '24:00']],
            '6': [['00:00', '00:45']]
        })
        self.assertEqual(new_avail, correct_avail)
def run_scheduler(registrations):
    """
    Runs the scheduler and prints a json containing a list of schedule objects
    to be written to the database.
    """
    # Convert registrations dict to students, tutors
    students = []
    tutors = []
    for registration in registrations:
        reg_id = registration['_id']
        availability = Availability.from_dict(registration['availability'])
        gender_preference = registration['genderPref']
        courses = registration['courses']
        earliest_start_date_str = registration['earliestStartTime']
        earliest_start_date = datetime.strptime(earliest_start_date_str,
                                                '%Y-%m-%d').date()
        user_dict = registration['user']
        user_id = user_dict['_id']
        gender = user_dict['gender'].upper()
        tz_string = user_dict['timezone']
        user_type = user_dict['role'].upper()
        user = User(user_id, reg_id, user_type, gender, gender_preference,
                    availability, tz_string, courses, earliest_start_date)
        if user_type == 'STUDENT':
            students.append(user)
        if user_type == 'TUTOR':
            tutors.append(user)

    # Run scheduler
    scheduler = Scheduler(students, tutors)
    schedule_dicts = scheduler.schedule_dicts_for_database()
    # print instead of return because python-shell receives this data from Python stdout
    print(json.dumps(schedule_dicts))
Exemple #10
0
 def test_forward_shifted_free_first_six_avail_forward(self):
     correct_shifted_avail = Availability.from_dict(
         {'0': [['00:15', '01:45']]})
     for i in range(-1, 2):
         shifted_avail = c.free_first_six_avail.forward_shifted(
             c.MINUTES_PER_WEEK * i + 15)
         self.assertEqual(shifted_avail, correct_shifted_avail)
Exemple #11
0
    def get_course_schedules(self):
        """
        Computes the datetimes of the course schedule in the student's timezone,
        in the tutor's timezone, and in UTC.

        Returns:
            student_course_schedule: A list of datetimes of course start times
                localized to the student's timezone.
            tutor_course_schedule: A list of datetimes of course start times
                localized to the tutor's timezone.
            UTC_course_schedule: A list of datetimes of course start times
                localized to UTC.
        """
        aware_UTC_start = pytz.utc.localize(self.earliest_course_start_UTC)
        earliest_course_start_student = aware_UTC_start.astimezone(self.student.tz)
        student_wt = Availability.new_timezone_wt(self.course_start_wt_UTC,
                                                  aware_UTC_start,
                                                  self.student.tz_str)
        student_first_course_dt = student_wt.first_datetime_after(earliest_course_start_student)
        student_course_schedule_naive = [student_first_course_dt
                                         + timedelta(days=Availability.DAYS_PER_WEEK*i)
                                         for i in range(self.weeks_per_course)]    
        student_course_schedule = map(self.student.tz.localize,
                                      student_course_schedule_naive)
        tutor_course_schedule = [student_dt.astimezone(self.tutor.tz)
                                 for student_dt in student_course_schedule]
        UTC_course_schedule = [student_dt.astimezone(pytz.utc)
                               for student_dt in student_course_schedule]
        return (student_course_schedule, tutor_course_schedule, UTC_course_schedule)
    def test_one_task_one_user_assign(self):
        start_a = datetime.datetime(2000, 1, 1, 6, 0, 0)
        end_a = datetime.datetime(2000, 1, 1, 22, 0, 0)
        availability = [Availability(Duration(start_a, end_a))]
        category = Category(1, 'TestCategory')
        preferences = [Preference(category, 0, True)]
        groups = [Group(1, 'Employee')]
        generic = CommonTestFunctions()

        staff_member = StaffMember(1, 'TestMember', 0, 40, 80, 10, availability, preferences, groups)

        start_t = datetime.datetime(2000, 1, 1, 9, 0, 0)
        end_t = datetime.datetime(2000, 1, 1, 16, 0, 0)
        task_time = Duration(start_t, end_t)
        location = Location(1, 'TestLocation')
        task = Task(1, 'TestTask', task_time, 1, groups[0], location, category)

        staff_members = [staff_member]
        roles = []
        tasks = [task]
        settings = generic.settings(40, True)
        generator = ScheduleGenerator(staff_members, roles, tasks)
        generator.schedule(settings) 
        self.assertTrue(staff_member.has_task(task))

        self.assertFalse(generator.has_unassigned_tasks())
Exemple #13
0
def webhook(request):
    if request.method == 'POST':
        requestData = request.data
        print requestData
        reqInfo = requestData['direction'] + ' - ' + requestData['moduleID']
        if 'replyData' in requestData:
            pass
            reqInfo += ' - ' + requestData['replyData']
        # print str(requestData['direction'] == 'out')
        if (requestData['moduleID'] == END_DATE_MODULEID and requestData['direction'] == 'in') or \
                (requestData['moduleID'] == CHECK_AVAILABILITY_MODULEID and requestData['direction'] == 'out'):
            reqInfo += ' - availability: '
            deviceRequest = MotionAI.checkAvailabilityFromBotData()
            print deviceRequest
            availability = Availability.CalculateAvailability(
                deviceRequest['fromDate'], deviceRequest['toDate'],
                deviceRequest['numberRequested'])
            if availability.available == True:
                pass
            else:
                pass

            # returnData = { "key1": 'wait and see', "key2": "value2" }
        # for r in returnData.values():
        #     print r
        returnData = {'key1': reqInfo}
        return Response(data=returnData, content_type='application/json')
Exemple #14
0
 def camp_availability(self,
                       day,
                       start_hour,
                       end_hour,
                       start_minute=0,
                       end_minute=0):
     start_a = datetime.datetime(2018, 7, day, start_hour, start_minute, 0)
     end_a = datetime.datetime(2018, 7, day, end_hour, end_minute, 0)
     return Availability(Duration(start_a, end_a))
Exemple #15
0
class TestAvailabilityClass(unittest.TestCase):
    def setUp(self):
        self.avail = Availability(0, 0, 0)
        self.avail_x = Availability(0, 5, 15)

    def test_100(self):
        avail_dict_100_res = {
            "monthly": 100.0,
            "yearly": 100.0,
            "daily": 100.0,
            "weekly": 100.0
        }
        avail_100_res = (100.0, 100.0, 100.0, 100.0)
        self.assertEqual(self.avail.service(out_dict=True), avail_dict_100_res)
        self.assertEqual(self.avail.service(), avail_100_res)

    def test_daily_100(self):
        avail_daily = {"daily": 100.0}
        avail_daily_t = (100.0)
        self.assertEqual(self.avail.service(period='daily', out_dict=True),
                         avail_daily)
        self.assertEqual(self.avail.service(period='daily'), avail_daily_t)

    def test_weekly_100(self):
        avail_weekly = {"weekly": 100.0}
        avail_weekly_t = (100.0)
        self.assertEqual(self.avail.service(period='weekly', out_dict=True),
                         avail_weekly)
        self.assertEqual(self.avail.service(period='weekly'), avail_weekly_t)

    def test_monthly_100(self):
        avail_monthly = {"monthly": 100.0}
        avail_monthly_t = (100.0)
        self.assertEqual(self.avail.service(period='monthly', out_dict=True),
                         avail_monthly)
        self.assertEqual(self.avail.service(period='monthly'), avail_monthly_t)

    def test_yearly_100(self):
        avail_yearly = {"yearly": 100.0}
        avail_yearly_t = (100.0)
        self.assertEqual(self.avail.service(period='yearly', out_dict=True),
                         avail_yearly)
        self.assertEqual(self.avail.service(period='yearly'), avail_yearly_t)
Exemple #16
0
    def assemble(database_availabilities,
                 database_days_off,
                 current_date=datetime.datetime.now()):
        availability = []
        converter = DateConverter()
        for time in database_availabilities:
            day = time.get_day_as_string()
            start_time = time.start_time
            end_time = time.end_time
            duration = Availability(
                converter.create_duration_on_next_day(day, day, start_time,
                                                      end_time, current_date))

            # Hack because the dateConverter isn't working properly but it'll work so we'll leave it.
            if day == 'Sunday':
                duration.start_time = duration.start_time - timedelta(days=7)
                duration.end_time = duration.end_time - timedelta(days=7)

            availability.append(duration)

        for day_off in database_days_off:
            if not day_off.get_is_approved():
                continue

            date = day_off.day
            start_time = datetime.datetime(date.year, date.month, date.day, 0,
                                           0)
            end_time = datetime.datetime(date.year, date.month, date.day, 23,
                                         59)
            duration = Duration(start_time, end_time)
            to_remove = []
            for a in availability:
                if a.can_happen_inside_of(duration):
                    to_remove.append(a)

            for t in to_remove:
                availability.remove(t)

        return availability
Exemple #17
0
 def test_new_timezone_wt_value_error(self):
     with self.assertRaises(ValueError):
         Availability.new_timezone_wt(WeeklyTime(0, 0, 14), c.utc_halloween,
                                      'UTC')
     with self.assertRaises(ValueError):
         Availability.new_timezone_wt(WeeklyTime(0, 0, 0), c.dt_2000_1_1,
                                      'UTC')
     with self.assertRaises(ValueError):
         Availability.new_timezone_wt(WeeklyTime(0, 0, 0), c.utc_halloween,
                                      'utc')
Exemple #18
0
 def test_shared_course_start_times_UTC_kabul_et_no_ds_overlap_one(self):
     user1 = c.new_user(
         c.student, {
             'tz_str': 'Asia/Kabul',
             'availability': c.free_first_six_avail,
             'earliest_start_date': c.dt_2000_1_1
         })
     avail = Availability.from_dict({'6': [['14:30', '16:00']]})
     user2 = c.new_user(
         c.student, {
             'tz_str': 'US/Eastern',
             'availability': avail,
             'earliest_start_date': date(2017, 3, 12)
         })
     shared = user1.shared_course_start_times_UTC(user2)
     self.assertEqual(shared, [WeeklyTime(6, 19, 30)])
Exemple #19
0
 def setUpClass(cls):
     with open("etc/environment.json") as f:
         cls.config = json.load(f)
     # os.environ["AWS_LAMBDA_FUNCTION_NAME"] = "test"
     os.environ["TOPIC"] = cls.config["Fn"]["TOPIC"]
     os.environ["TABLE"] = cls.config["Fn"]["TABLE"]
     cls.av = Availability()
     cls.av.logging = False
     cls.av.pull_config()
     cls.user = "******"
     cls.store = "cvs"
     cls.notification = {
         "store":
         "CVS",
         "availability_at": [
             "BROWNS MILLS", "ELIZABETH", "ENGLEWOOD", "EWING", "GIBBSBORO",
             "GLASSBORO", "LAWRENCEVILE", "LODI", "LONG BRANCH",
             "NORTH BRUNSWICK", "NORTH PLAINFIELD", "PENNSAUKEN",
             "PLAINSBORO", "TEANECK", "WEST ORANGE", "WILLINGBORO"
         ]
     }
     cls.context = Context()
Exemple #20
0
 def availability(self, start_hour=6, end_hour=22, start_day=1, end_day=1):
     return Availability(
         self.duration(start_hour, end_hour, 0, 0, start_day, end_day))
Exemple #21
0
 def test_UTC_offset_minutes_no_offset(self):
     self.assertEqual(Availability.UTC_offset_minutes(c.utc_halloween), 0)
Exemple #22
0
 def availability(self, pk):
     raw_availability = FareHarborService().get_availability(
         self.shortname, pk)
     availability_data = raw_availability['availability']
     return Availability(availability_data)
Exemple #23
0
 def availabilities_by_date_range(self, data):
     raw_availabilities = FareHarborService(
     ).get_availabilities_by_date_range(self.shortname, data)
     availabilities_data = raw_availabilities['availabilities']
     return [Availability(i) for i in availabilities_data]
Exemple #24
0
 def test_time_str_to_index_value_error(self):
     with self.assertRaises(ValueError):
         Availability.time_str_to_index('0000')
     with self.assertRaises(ValueError):
         Availability.time_str_to_index('0:00')
     with self.assertRaises(ValueError):
         Availability.time_str_to_index('0:000')
     with self.assertRaises(ValueError):
         Availability.time_str_to_index('25:00')
     with self.assertRaises(ValueError):
         Availability.time_str_to_index('00:60')
     with self.assertRaises(ValueError):
         Availability.time_str_to_index('00:59')
Exemple #25
0
 def test_time_str_to_index_2400(self):
     self.assertEqual(Availability.time_str_to_index('24:00'), 96)
Exemple #26
0
 def test_time_str_to_index_2345(self):
     self.assertEqual(Availability.time_str_to_index('23:45'), 95)
Exemple #27
0
 def test_time_str_to_index_0030(self):
     self.assertEqual(Availability.time_str_to_index('00:30'), 2)
Exemple #28
0
 def test_time_str_to_index_0015(self):
     self.assertEqual(Availability.time_str_to_index('00:15'), 1)
Exemple #29
0
 def test_UTC_offset_minutes_pos_offset(self):
     self.assertEqual(Availability.UTC_offset_minutes(c.kabul_2000_1_1),
                      270)
     self.assertEqual(Availability.UTC_offset_minutes(c.kathmandu_2017_end),
                      345)
Exemple #30
0
 def test_new_timezone_wt_same_tz(self):
     new_wt = Availability.new_timezone_wt(c.sunday_0000, c.utc_halloween,
                                           'UTC')
     self.assertEqual(new_wt, c.sunday_0000)