1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347
|
from __future__ import annotations
import heapq
import operator
import pickle
import random
import pytest
from distributed.collections import LRU, HeapSet
def test_lru():
l = LRU(maxsize=3)
l["a"] = 1
l["b"] = 2
l["c"] = 3
assert list(l.keys()) == ["a", "b", "c"]
# Use "a" and ensure it becomes the most recently used item
l["a"]
assert list(l.keys()) == ["b", "c", "a"]
# Ensure maxsize is respected
l["d"] = 4
assert len(l) == 3
assert list(l.keys()) == ["c", "a", "d"]
class C:
def __init__(self, k, i):
self.k = k
self.i = i
def __hash__(self):
return hash(self.k)
def __eq__(self, other):
return isinstance(other, C) and other.k == self.k
def __repr__(self):
return f"C({self.k}, {self.i})"
def test_heapset():
heap = HeapSet(key=operator.attrgetter("i"))
cx = C("x", 2)
cy = C("y", 1)
cz = C("z", 3)
cw = C("w", 4)
heap.add(cx)
heap.add(cy)
heap.add(cz)
heap.add(cw)
heap.add(C("x", 0)) # Ignored; x already in heap
assert len(heap) == 4
assert repr(heap) == "<HeapSet: 4 items>"
assert cx in heap
assert cy in heap
assert cz in heap
assert cw in heap
heap_sorted = heap.sorted()
# iteration does not empty heap
assert len(heap) == 4
assert next(heap_sorted) is cy
assert next(heap_sorted) is cx
assert next(heap_sorted) is cz
assert next(heap_sorted) is cw
with pytest.raises(StopIteration):
next(heap_sorted)
assert set(heap) == {cx, cy, cz, cw}
assert heap.peek() is cy
assert heap.pop() is cy
assert cx in heap
assert cy not in heap
assert cz in heap
assert cw in heap
assert heap.peek() is cx
assert heap.pop() is cx
assert heap.pop() is cz
assert heap.pop() is cw
assert not heap
with pytest.raises(KeyError):
heap.pop()
with pytest.raises(KeyError):
heap.peek()
# Test out-of-order discard
heap.add(cx)
heap.add(cy)
heap.add(cz)
heap.add(cw)
assert heap.peek() is cy
heap.remove(cy)
assert cy not in heap
with pytest.raises(KeyError):
heap.remove(cy)
heap.discard(cw)
assert cw not in heap
heap.discard(cw)
assert len(heap) == 2
assert list(heap.sorted()) == [cx, cz]
# cy is at the top of heap._heap, but is skipped
assert heap.peek() is cx
assert heap.pop() is cx
assert heap.peek() is cz
assert heap.pop() is cz
# heap._heap is not empty
assert not heap
with pytest.raises(KeyError):
heap.peek()
with pytest.raises(KeyError):
heap.pop()
assert list(heap.sorted()) == []
# Test clear()
heap.add(cx)
heap.clear()
assert not heap
heap.add(cx)
assert cx in heap
# Test discard last element
heap.discard(cx)
assert not heap
heap.add(cx)
assert cx in heap
# Test peekn()
heap.add(cy)
heap.add(cw)
heap.add(cz)
heap.add(cx)
assert list(heap.peekn(3)) == [cy, cx, cz]
heap.remove(cz)
assert list(heap.peekn(10)) == [cy, cx, cw]
assert list(heap.peekn(0)) == []
assert list(heap.peekn(-1)) == []
heap.remove(cy)
assert list(heap.peekn(1)) == [cx]
heap.remove(cw)
assert list(heap.peekn(1)) == [cx]
heap.remove(cx)
assert list(heap.peekn(-1)) == []
assert list(heap.peekn(0)) == []
assert list(heap.peekn(1)) == []
assert list(heap.peekn(2)) == []
# Test resilience to failure in key()
heap.add(cx)
bad_key = C("bad_key", 0)
del bad_key.i
with pytest.raises(AttributeError):
heap.add(bad_key)
assert len(heap) == 1
assert set(heap) == {cx}
# Test resilience to failure in weakref.ref()
class D:
__slots__ = ("i",)
def __init__(self, i):
self.i = i
with pytest.raises(TypeError):
heap.add(D("bad_weakref", 2))
assert len(heap) == 1
assert set(heap) == {cx}
# Test resilience to key() returning non-sortable output
with pytest.raises(TypeError):
heap.add(C("unsortable_key", None))
assert len(heap) == 1
assert set(heap) == {cx}
def assert_heap_sorted(heap: HeapSet) -> None:
assert heap._sorted
assert heap._heap == sorted(heap._heap)
def test_heapset_sorted_flag_left():
heap = HeapSet(key=operator.attrgetter("i"))
assert heap._sorted
c1 = C("1", 1)
c2 = C("2", 2)
c3 = C("3", 3)
c4 = C("4", 4)
heap.add(c4)
assert not heap._sorted
heap.add(c3)
heap.add(c2)
heap.add(c1)
list(heap.sorted())
assert_heap_sorted(heap)
# `peek` maintains sort if first element is not discarded
assert heap.peek() is c1
assert_heap_sorted(heap)
# `pop` always de-sorts
assert heap.pop() is c1
assert not heap._sorted
list(heap.sorted())
# discard first element
heap.discard(c2)
assert heap.peek() is c3
assert not heap._sorted
# popping the last element resets the sorted flag
assert heap.pop() is c3
assert heap.pop() is c4
assert not heap
assert_heap_sorted(heap)
# discarding`` the last element resets the sorted flag
heap.add(c1)
heap.add(c2)
assert not heap._sorted
heap.discard(c1)
assert not heap._sorted
heap.discard(c2)
assert not heap
assert_heap_sorted(heap)
def test_heapset_sorted_flag_right():
"Verify right operations don't affect sortedness"
heap = HeapSet(key=operator.attrgetter("i"))
c1 = C("1", 1)
c2 = C("2", 2)
c3 = C("3", 3)
heap.add(c2)
heap.add(c3)
heap.add(c1)
assert not heap._sorted
list(heap.sorted())
assert_heap_sorted(heap)
assert heap.peekright() is c3
assert_heap_sorted(heap)
assert heap.popright() is c3
assert_heap_sorted(heap)
assert heap.popright() is c2
assert_heap_sorted(heap)
heap.add(c2)
assert not heap._sorted
assert heap.popright() is c2
assert not heap._sorted
assert heap.popright() is c1
assert not heap
assert_heap_sorted(heap)
@pytest.mark.parametrize("peek", [False, True])
def test_heapset_popright(peek):
heap = HeapSet(key=operator.attrgetter("i"))
with pytest.raises(KeyError):
heap.peekright()
with pytest.raises(KeyError):
heap.popright()
# The heap contains broken weakrefs
for i in range(200):
c = C(f"y{i}", random.random())
heap.add(c)
if random.random() > 0.7:
heap.remove(c)
c0 = heap.peek()
while len(heap) > 1:
# These two code paths determine which of the two methods deals with the
# removal of broken weakrefs
if peek:
c1 = heap.peekright()
assert c1.i >= c0.i
assert heap.popright() is c1
else:
c1 = heap.popright()
assert c1.i >= c0.i
# Test that the heap hasn't been corrupted
h2 = heap._heap[:]
heapq.heapify(h2)
assert h2 == heap._heap
assert heap.peekright() is c0
assert heap.popright() is c0
assert not heap
def test_heapset_pickle():
"""Test pickle roundtrip for a HeapSet.
Note
----
To make this test work with plain pickle and not need cloudpickle, we had to avoid
lambdas and local classes in our test. Here we're testing that HeapSet doesn't add
lambdas etc. of its own.
"""
heap = HeapSet(key=operator.attrgetter("i"))
# The heap contains broken weakrefs
for i in range(200):
c = C(f"y{i}", random.random())
heap.add(c)
if random.random() > 0.7:
heap.remove(c)
list(heap.sorted()) # trigger sort
assert heap._sorted
heap2 = pickle.loads(pickle.dumps(heap))
assert len(heap) == len(heap2)
assert not heap2._sorted # re-heapification may have broken the sort
# Test that the heap has been re-heapified upon unpickle
assert len(heap2._heap) < len(heap._heap)
while heap:
assert heap.pop() == heap2.pop()
def test_heapset_sort_duplicate():
"""See https://github.com/dask/distributed/issues/6951"""
heap = HeapSet(key=operator.attrgetter("i"))
c1 = C("x", 1)
c2 = C("2", 2)
heap.add(c1)
heap.add(c2)
heap.discard(c1)
heap.add(c1)
assert list(heap.sorted()) == [c1, c2]
|