from datetime import datetime, timedelta, timezone
from django.test import TestCase
from AKModel.availability.models import Availability
from AKModel.models import AK, AKSlot, Event
from AKPreference.models import AKPreference, EventParticipant
from AKSolverInterface.serializers import ExportEventSerializer
[docs]
class JSONExportScheduledSlotsTest(TestCase):
"""Test that scheduled slots are removed from the export when fixing scheduled slots
and that availabilities of affected objects are reduced accordingly."""
fixtures = ["model.json"]
def setUp(self):
self.event = Event.objects.get(pk=2)
# AK 3 conflicts with AK 1 and has AK 2 as prerequisite
self.ak_wish = AK.objects.get(pk=3)
Availability.with_event_length(event=self.event, ak=self.ak_wish).save()
self.participant = EventParticipant.objects.create(event=self.event, name="Required participant")
AKPreference.objects.create(event=self.event, participant=self.participant, ak=AK.objects.get(pk=2),
preference=AKPreference.PreferenceLevel.REQUIRED)
self.scheduled_slots = list(AKSlot.objects.filter(event=self.event, start__isnull=False))
def _export(self, fixed: bool) -> dict:
return ExportEventSerializer(self.event, export_scheduled_aks_as_fixed=fixed).data
@staticmethod
def _timeslots(export: dict):
for block in export["timeslots"]["blocks"]:
for timeslot in block:
yield timeslot
def _timeslot_avail(self, timeslot: dict) -> Availability:
def _parse(value: str) -> datetime:
return datetime.strptime(value, "%Y-%m-%d %H:%M").replace(tzinfo=self.event.timezone)
return Availability(event=self.event, start=_parse(timeslot["info"]["start"]),
end=_parse(timeslot["info"]["end"]))
def _fulfilling_timeslots(self, export: dict, constraint: str) -> list[Availability]:
return [
self._timeslot_avail(timeslot) for timeslot in self._timeslots(export)
if constraint in timeslot["fulfilled_time_constraints"]
]
[docs]
def test_scheduled_slots_removed(self):
"""Scheduled slots are only exported if scheduled slots are not fixed."""
scheduled_pks = {slot.pk for slot in self.scheduled_slots}
self.assertTrue(scheduled_pks <= {ak["id"] for ak in self._export(fixed=False)["aks"]})
export = self._export(fixed=True)
exported_pks = {ak["id"] for ak in export["aks"]}
self.assertFalse(scheduled_pks & exported_pks)
for participant in export["participants"]:
self.assertFalse(scheduled_pks & {pref["ak_id"] for pref in participant["preferences"]})
[docs]
def test_owner_availability_reduced(self):
"""Owners are not available during their scheduled slots."""
export = self._export(fixed=True)
for slot in self.scheduled_slots:
slot_avail = Availability(event=self.event, start=slot.start, end=slot.end)
for owner in slot.ak.owners.all():
with self.subTest(slot=slot, owner=owner):
timeslots = self._fulfilling_timeslots(export, f"availability-person-{owner.pk}")
self.assertTrue(timeslots)
self.assertFalse(any(t.overlaps(slot_avail, strict=True) for t in timeslots))
# remaining slot of AK 1 is constrained by its owner
remaining_slot = next(ak for ak in export["aks"] if ak["id"] == 5)
self.assertIn("availability-person-1", remaining_slot["time_constraints"])
[docs]
def test_room_availability_reduced(self):
"""Rooms are not available during slots scheduled in them."""
slots_with_room = [slot for slot in self.scheduled_slots if slot.room is not None]
self.assertTrue(slots_with_room)
for slot in slots_with_room:
Availability.with_event_length(event=self.event, room=slot.room).save()
unfixed_rooms = {room["id"]: room for room in self._export(fixed=False)["rooms"]}
for slot in slots_with_room:
self.assertFalse(unfixed_rooms[slot.room.pk]["time_constraints"])
export = self._export(fixed=True)
for slot in slots_with_room:
with self.subTest(slot=slot):
constraint = f"availability-room-{slot.room.pk}"
room = next(r for r in export["rooms"] if r["id"] == slot.room.pk)
self.assertIn(constraint, room["time_constraints"])
slot_avail = Availability(event=self.event, start=slot.start, end=slot.end)
timeslots = self._fulfilling_timeslots(export, constraint)
self.assertTrue(timeslots)
self.assertFalse(any(t.overlaps(slot_avail, strict=True) for t in timeslots))
[docs]
def test_owner_without_remaining_availability(self):
"""Owners whose whole availability is used by scheduled slots cannot be scheduled anymore."""
slot = AKSlot.objects.get(pk=2)
owner = slot.ak.owners.get()
Availability.objects.create(event=self.event, person=owner, start=slot.start, end=slot.end)
# unscheduled slot of the same owner
AKSlot.objects.create(event=self.event, ak=slot.ak, duration=1)
export = self._export(fixed=True)
constraint = f"availability-person-{owner.pk}"
for ak in export["aks"]:
if ak["info"]["django_ak_id"] == slot.ak.pk:
self.assertIn(constraint, ak["time_constraints"])
self.assertFalse(self._fulfilling_timeslots(export, constraint))
[docs]
def test_participant_without_remaining_availability(self):
"""Participants whose whole availability is used by scheduled slots get a time constraint."""
slot = AKSlot.objects.get(pk=2)
Availability.objects.create(event=self.event, participant=self.participant, start=slot.start, end=slot.end)
export = self._export(fixed=True)
constraint = f"availability-participant-{self.participant.pk}"
participant = next(p for p in export["participants"] if p["id"] == self.participant.pk)
self.assertIn(constraint, participant["time_constraints"])
self.assertFalse(self._fulfilling_timeslots(export, constraint))
[docs]
def test_prerequisite_ak_availability_reduced(self):
"""Prerequisites of a scheduled AK are only available before its start."""
# schedule a slot of AK 3, which has AK 2 as prerequisite
AKSlot.objects.get(pk=2).unschedule()
Availability.with_event_length(event=self.event, ak=AK.objects.get(pk=2)).save()
wish_slot = AKSlot.objects.get(pk=3)
wish_slot.start = datetime(2020, 11, 8, 12, 0, tzinfo=timezone.utc)
wish_slot.save()
timeslots = self._fulfilling_timeslots(self._export(fixed=True), "availability-ak-2")
self.assertTrue(timeslots)
self.assertTrue(all(t.end <= wish_slot.start for t in timeslots))
[docs]
def test_filtered_scheduled_slots_considered(self):
"""Scheduled slots excluded by filters still reduce availabilities."""
slot = AKSlot.objects.get(pk=2)
owner = slot.ak.owners.get()
slot_avail = Availability(event=self.event, start=slot.start, end=slot.end)
export = ExportEventSerializer(
self.event, export_scheduled_aks_as_fixed=True,
filter_slots_cb=lambda queryset: queryset.exclude(ak=slot.ak),
).data
timeslots = self._fulfilling_timeslots(export, f"availability-person-{owner.pk}")
self.assertTrue(timeslots)
self.assertFalse(any(t.overlaps(slot_avail, strict=True) for t in timeslots))
[docs]
def test_no_fixed_slot_constraints(self):
"""Timeslots do not fulfill constraints of fixed slots that are not exported."""
export = self._export(fixed=True)
for timeslot in self._timeslots(export):
self.assertFalse([c for c in timeslot["fulfilled_time_constraints"] if c.startswith("fixed-akslot-")])
[docs]
def test_required_participant_availability_reduced(self):
"""Participants are not available during scheduled slots they are required for."""
export = self._export(fixed=True)
slot = AKSlot.objects.get(pk=2)
slot_avail = Availability(event=self.event, start=slot.start, end=slot.end)
participant = next(p for p in export["participants"] if p["id"] == self.participant.pk)
constraint = f"availability-participant-{self.participant.pk}"
self.assertIn(constraint, participant["time_constraints"])
timeslots = self._fulfilling_timeslots(export, constraint)
self.assertTrue(timeslots)
self.assertFalse(any(t.overlaps(slot_avail, strict=True) for t in timeslots))
[docs]
def test_dependent_ak_availability_reduced(self):
"""AKs depending on a scheduled AK are only available after its end."""
export = self._export(fixed=True)
prerequisite_end = AKSlot.objects.get(pk=2).end
timeslots = self._fulfilling_timeslots(export, "availability-ak-3")
self.assertTrue(timeslots)
self.assertTrue(all(t.start >= prerequisite_end for t in timeslots))
for ak in export["aks"]:
if ak["info"]["django_ak_id"] == 3:
self.assertIn("availability-ak-3", ak["time_constraints"])
[docs]
def test_conflicting_ak_availability_reduced_both_ways(self):
"""Conflicts are considered in both directions."""
# move slot of AK 1 (conflicting with AK 3) into the timeslots
slot = AKSlot.objects.get(pk=1)
slot.start = datetime(2020, 11, 9, 20, 0, tzinfo=timezone.utc)
slot.save()
slot_avail = Availability(event=self.event, start=slot.start, end=slot.end)
timeslots = self._fulfilling_timeslots(self._export(fixed=True), "availability-ak-3")
self.assertTrue(timeslots)
self.assertFalse(any(t.overlaps(slot_avail, strict=True) for t in timeslots))
# AK 1 is not available during a scheduled slot of AK 3
slot.unschedule()
Availability.with_event_length(event=self.event, ak=slot.ak).save()
wish_slot = AKSlot.objects.get(pk=3)
wish_slot.start = datetime(2020, 11, 9, 20, 0, tzinfo=timezone.utc)
wish_slot.save()
wish_avail = Availability(event=self.event, start=wish_slot.start, end=wish_slot.end)
timeslots = self._fulfilling_timeslots(self._export(fixed=True), "availability-ak-1")
self.assertTrue(timeslots)
self.assertFalse(any(t.overlaps(wish_avail, strict=True) for t in timeslots))
[docs]
class AvailabilityDifferenceTest(TestCase):
"""Test computing the difference of availabilities."""
def test_difference(self):
base = datetime(2020, 1, 1, tzinfo=timezone.utc)
def _avail(start_hour: int, end_hour: int) -> Availability:
return Availability(start=base + timedelta(hours=start_hour), end=base + timedelta(hours=end_hour))
def _hours(avails: list[Availability]) -> list[tuple[int, int]]:
return [(int((a.start - base).total_seconds() // 3600), int((a.end - base).total_seconds() // 3600))
for a in avails]
self.assertEqual(_hours(Availability.difference([_avail(0, 10)], [_avail(2, 4)])), [(0, 2), (4, 10)])
self.assertEqual(_hours(Availability.difference([_avail(0, 10)], [_avail(0, 4), _avail(8, 12)])),
[(4, 8)])
self.assertEqual(_hours(Availability.difference([_avail(0, 2), _avail(5, 7)], [_avail(1, 6)])),
[(0, 1), (6, 7)])
self.assertEqual(_hours(Availability.difference([_avail(0, 2)], [_avail(2, 4)])), [(0, 2)])
self.assertEqual(Availability.difference([_avail(1, 2)], [_avail(0, 4)]), [])
self.assertEqual(Availability.difference([], [_avail(0, 4)]), [])