Example #1
0
def create_entry(name, priority, start, stop, interval, action, cb_url=None):
    kwargs = {
        "name": name,
        "priority": priority,
        "stop": stop,
        "interval": interval,
        "action": action,
        "owner": User.objects.get_or_create(username="******")[0],
    }

    if start is not None:
        kwargs["start"] = start

    if cb_url is not None:
        kwargs["callback_url"] = cb_url

    r = Request()
    r.scheme = "https"
    r.version = V1["version"]
    r.host = "testserver"
    r.save()
    schedule_entry = ScheduleEntry(**kwargs)
    schedule_entry.request = r
    schedule_entry.save()

    return schedule_entry
Example #2
0
def test_bad_interval_raises():
    with pytest.raises(ValidationError):
        ScheduleEntry(name='t', interval=-1, action='logger').clean_fields()
    with pytest.raises(ValidationError):
        ScheduleEntry(name='t', interval=0, action='logger').clean_fields()
    with pytest.raises(ValidationError):
        ScheduleEntry(name='t', interval=0.1, action='logger').clean_fields()
Example #3
0
def test_bad_name_raises():
    with pytest.raises(ValidationError):  # whitespace
        ScheduleEntry(name="test 1", action="logger").clean_fields()
    with pytest.raises(ValidationError):  # punctuation other than "_-"
        ScheduleEntry(name="test1!", action="logger").clean_fields()

    # ok
    ScheduleEntry(name="_test-Stuff123", action="logger").clean_fields()
Example #4
0
def test_bad_name_raises():
    with pytest.raises(ValidationError):  # whitespace
        ScheduleEntry(name='test 1', action='logger').clean_fields()
    with pytest.raises(ValidationError):  # punctuation other than "_-"
        ScheduleEntry(name='test1!', action='logger').clean_fields()

    # ok
    ScheduleEntry(name='_test-Stuff123', action='logger').clean_fields()
Example #5
0
def test_relative_stop_becomes_absolute():
    e = ScheduleEntry(name='t',
                      start=20,
                      relative_stop=10,
                      interval=1,
                      action='logger')
    assert e.start == 20
    assert e.stop == 30
    assert list(e.get_remaining_times()) == list(range(20, 30, 1))
Example #6
0
def test_take_until(test_input, future_t, expected):
    start, stop, interval = test_input
    entry = ScheduleEntry(name='t', start=start, stop=stop, interval=interval,
                          action='logger')
    initial_times = list(entry.get_remaining_times())
    r = []
    for t in count(future_t, future_t):
        ts = list(entry.take_until(t))
        if not ts:
            break
        r.append(ts)

    assert r == expected
    assert initial_times == list(flatten(r))
Example #7
0
def test_defaults():
    entry = ScheduleEntry(name='t', action='logger')
    assert entry.priority == DEFAULT_PRIORITY
    assert entry.start is not None
    assert entry.stop is None
    assert entry.interval is None
    assert entry.is_active
Example #8
0
def test_no_interval_with_start_is_one_shot():
    """Specifying start should not affect number of times."""
    e = ScheduleEntry(name='t', action='logger', start=1)
    remaining_times = list(e.get_remaining_times())
    assert len(remaining_times) == 1

    times = list(e.take_until(remaining_times[0] + 1000))
    assert len(times) == 1

    # when interval is None, consuming the single task time unsets `active`
    assert not e.is_active
    assert not list(e.get_remaining_times())
    assert not list(e.take_until(remaining_times[0] + 1000))
Example #9
0
def test_no_interval_is_one_shot():
    """Leaving `interval` blank should indicate "one-shot" entry."""
    e = ScheduleEntry(name='t', action='logger')
    remaining_times = list(e.get_remaining_times())
    assert len(remaining_times) == 1

    times = list(e.take_until(remaining_times[0] + 1000))
    assert len(times) == 1

    # when interval is None, consuming the single task time unsets `active`
    assert not e.is_active
    assert not list(e.get_remaining_times())
    assert not list(e.take_until(remaining_times[0] + 1000))
Example #10
0
def test_no_interval_future_start(testclock):
    """One-shot entry should wait for start."""
    # recall current t=0 so start=1 is 1 second in the future
    e = ScheduleEntry(name='t', action='logger', start=1)
    assert not e.take_pending()
Example #11
0
def test_stop_before_start():
    e = ScheduleEntry(name='t', start=20, stop=10, interval=1, action='logger')
    assert list(e.get_remaining_times()) == list(range(0))
Example #12
0
def test_undefined_stop_is_never():
    entry = ScheduleEntry(name='t', action='logger', interval=1)
    assert entry.stop is None
    assert type(entry.get_remaining_times()) is itertools.count
Example #13
0
def test_undefined_start_is_now():
    entry = ScheduleEntry(name='t', action='logger')
    now = utils.timefn()
    assert entry.start in (now - 1, now, now + 1)
Example #14
0
def test_str():
    str(ScheduleEntry(name='t', action='logger'))
Example #15
0
def test_str():
    str(ScheduleEntry(name="t", action="logger"))
Example #16
0
def test_non_unique_name_raises(user):
    ScheduleEntry(name='t', action='logger', owner=user).save()
    with pytest.raises(ValidationError):
        ScheduleEntry(name='t', action='logger', owner=user).full_clean()
Example #17
0
def test_bad_action_raises():
    with pytest.raises(ValidationError):
        ScheduleEntry(name='t', action='this_doesnt_exist').clean_fields()
    def handle(self, *args, **options):
        self.stdout.write("Beginning assignment for %d week(s)." % options["weeks"])

        # fetch all accounts
        accounts = Account.objects.all()
        assigned = 0

        # try to find the last assignment
        last_assignments = TallyListEntry.objects.filter(processed=False).order_by("created_at")
        if len(last_assignments) > 0:
            last_assignment = last_assignments[0].created_at
        else:
            last_assignment = datetime.datetime.now()
        number_of_days = (datetime.datetime.now() - datetime.datetime(last_assignment.year, last_assignment.month, last_assignment.day)).days

        self.stdout.write("Last assignment was on %s (%d days ago)" % (last_assignment, number_of_days))

        # try to find the month we start at
        schedule_entries = ScheduleEntry.objects.filter(type__in=["w", "b"]).order_by('-date')
        if len(schedule_entries) > 0:
            week = schedule_entries[0].date
            type = schedule_entries[0].type

            type = "w" if type == "b" else "b"
            week += datetime.timedelta(weeks=1)
        else:
            now = datetime.datetime.now()
            week = datetime.date(now.year, now.month, now.day)
            type = "w"

        # get the next friday for cleaning
        week = next_weekday(week, 4)

        while assigned < options["weeks"]:
            self.stdout.write("Looking for %s cleaning for %s" % (type, week))

            # at first update the assignment values based on coffee consumption
            for account in accounts:
                coffee_count = 0
                coffees = TallyListEntry.objects.filter(user=account, processed=False)

                for coffee in coffees:
                    coffee_count += coffee.amount
                    coffee.processed = True
                    coffee.save()

                account.assignment_value += coffee_count / float(max(1, number_of_days))
                account.save()

            # assign the user with the highest value
            assigned_user = None
            for account in accounts:
                account.assignment_value += 1
                account.save()
                if not assigned_user or assigned_user.assignment_value < account.assignment_value:
                    assigned_user = account

            # we found one!
            if assigned_user:
                self.stdout.write("User assigned: %s" % assigned_user.get_full_name())
                assigned += 1

                assigned_user.assignment_value = assigned_user.assignment_base
                assigned_user.save()

                entry = ScheduleEntry(user=assigned_user,
                                      date=week,
                                      type=type,
                                      done=False)
                entry.save()
            else:
                self.stderr.write("No user could be assigned!")
                break

            type = "w" if type == "b" else "b"
            week += datetime.timedelta(weeks=1)

        self.stdout.write("Assignment complete.")
Example #19
0
def test_no_interval():
    e1 = ScheduleEntry(name='t', action='logger')
    remaining_times = list(e1.get_remaining_times())
    assert len(remaining_times) == 1

    times = list(e1.take_until(remaining_times[0] + 1000))
    assert len(times) == 1

    # when interval is None, consuming the single task time unsets `active`
    assert not e1.is_active
    assert not list(e1.get_remaining_times())
    assert not list(e1.take_until(remaining_times[0] + 1000))

    e2 = ScheduleEntry(name='t', action='logger', start=1)
    remaining_times = list(e2.get_remaining_times())
    assert len(remaining_times) == 1

    times = list(e2.take_until(remaining_times[0] + 1000))
    assert len(times) == 1

    # when interval is None, consuming the single task time unsets `active`
    assert not e2.is_active
    assert not list(e2.get_remaining_times())
    assert not list(e2.take_until(remaining_times[0] + 1000))