Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions src/calendar_queue/calendar_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
from asyncio import Queue, QueueFull, TimerHandle
from heapq import heappop as heap_pop
from heapq import heappush as heap_push
from heapq import heapify
import math
import sys
from time import time
Expand Down Expand Up @@ -237,6 +238,10 @@ def delete_items(
if selector(item):
del_items.append(self._queue.pop(q_len - 1 - i))

# Restore heap invariant after arbitrary deletions.
if del_items:
heapify(self._queue)

self._update_timer()

return del_items
35 changes: 35 additions & 0 deletions tests/test_calendar_queue.py
Original file line number Diff line number Diff line change
Expand Up @@ -111,6 +111,41 @@ async def test_delete_items():
assert cq.qsize() == 5


@pytest.mark.asyncio
async def test_delete_restores_heap_property():
"""Ensure deleting arbitrary items restores the heap property so
subsequent pops return items in increasing timestamp order.
"""

cq = CalendarQueue()

base_ts = time()

items = [
(base_ts + 10, "a"),
(base_ts + 20, "b"),
(base_ts + 30, "c"),
(base_ts + 40, "d"),
]

for item in items:
cq.put_nowait(item)

# remove the middle element
deleted = cq.delete_items(lambda x: x[1] == "b")

assert len(deleted) == 1 and deleted[0] == (base_ts + 20, "b")

popped = []
while cq.qsize() > 0:
popped.append(cq.get_nowait())

assert [p[1] for p in popped] == ["a", "c", "d"]
assert popped[0][0] == pytest.approx(base_ts + 10, abs=ABS_TOLERANCE)
assert popped[1][0] == pytest.approx(base_ts + 30, abs=ABS_TOLERANCE)
assert popped[2][0] == pytest.approx(base_ts + 40, abs=ABS_TOLERANCE)


@pytest.mark.asyncio
async def test_far_schedule():
"""Test putting an event scheduled far in time.
Expand Down
Loading