| 1 |
from __future__ import annotations |
| 2 |
|
| 3 |
import re |
| 4 |
import weakref |
| 5 |
from collections.abc import Callable |
| 6 |
from typing import TypeAlias |
| 7 |
|
| 8 |
import pytest |
| 9 |
|
| 10 |
from .. import _core |
| 11 |
from .._core._parking_lot import GLOBAL_PARKING_LOT_BREAKER |
| 12 |
from .._sync import * |
| 13 |
from .._timeouts import sleep_forever |
| 14 |
from ..testing import assert_checkpoints, wait_all_tasks_blocked |
| 15 |
|
| 16 |
|
| 17 |
async def test_Event() -> None: |
| 18 |
e = Event() |
| 19 |
assert not e.is_set() |
| 20 |
assert e.statistics().tasks_waiting == 0 |
| 21 |
|
| 22 |
with pytest.raises(NotImplementedError): |
| 23 |
e.__bool__() |
| 24 |
|
| 25 |
e.set() |
| 26 |
assert e.is_set() |
| 27 |
with assert_checkpoints(): |
| 28 |
await e.wait() |
| 29 |
|
| 30 |
e = Event() |
| 31 |
|
| 32 |
record = [] |
| 33 |
|
| 34 |
async def child() -> None: |
| 35 |
record.append("sleeping") |
| 36 |
await e.wait() |
| 37 |
record.append("woken") |
| 38 |
|
| 39 |
async with _core.open_nursery() as nursery: |
| 40 |
nursery.start_soon(child) |
| 41 |
nursery.start_soon(child) |
| 42 |
await wait_all_tasks_blocked() |
| 43 |
assert record == ["sleeping", "sleeping"] |
| 44 |
assert e.statistics().tasks_waiting == 2 |
| 45 |
e.set() |
| 46 |
await wait_all_tasks_blocked() |
| 47 |
assert record == ["sleeping", "sleeping", "woken", "woken"] |
| 48 |
|
| 49 |
|
| 50 |
async def test_CapacityLimiter() -> None: |
| 51 |
assert CapacityLimiter(0).total_tokens == 0 |
| 52 |
with pytest.raises(TypeError): |
| 53 |
CapacityLimiter(1.0) |
| 54 |
with pytest.raises(ValueError, match=r"^total_tokens must be >= 0$"): |
| 55 |
CapacityLimiter(-1) |
| 56 |
c = CapacityLimiter(2) |
| 57 |
repr(c) # smoke test |
| 58 |
assert c.total_tokens == 2 |
| 59 |
assert c.borrowed_tokens == 0 |
| 60 |
assert c.available_tokens == 2 |
| 61 |
with pytest.raises(RuntimeError): |
| 62 |
c.release() |
| 63 |
assert c.borrowed_tokens == 0 |
| 64 |
c.acquire_nowait() |
| 65 |
assert c.borrowed_tokens == 1 |
| 66 |
assert c.available_tokens == 1 |
| 67 |
|
| 68 |
stats = c.statistics() |
| 69 |
assert stats.borrowed_tokens == 1 |
| 70 |
assert stats.total_tokens == 2 |
| 71 |
assert stats.borrowers == [_core.current_task()] |
| 72 |
assert stats.tasks_waiting == 0 |
| 73 |
|
| 74 |
# Can't re-acquire when we already have it |
| 75 |
with pytest.raises(RuntimeError): |
| 76 |
c.acquire_nowait() |
| 77 |
assert c.borrowed_tokens == 1 |
| 78 |
with pytest.raises(RuntimeError): |
| 79 |
await c.acquire() |
| 80 |
assert c.borrowed_tokens == 1 |
| 81 |
|
| 82 |
# We can acquire on behalf of someone else though |
| 83 |
with assert_checkpoints(): |
| 84 |
await c.acquire_on_behalf_of("someone") |
| 85 |
|
| 86 |
# But then we've run out of capacity |
| 87 |
assert c.borrowed_tokens == 2 |
| 88 |
with pytest.raises(_core.WouldBlock): |
| 89 |
c.acquire_on_behalf_of_nowait("third party") |
| 90 |
|
| 91 |
assert set(c.statistics().borrowers) == {_core.current_task(), "someone"} |
| 92 |
|
| 93 |
# Until we release one |
| 94 |
c.release_on_behalf_of(_core.current_task()) |
| 95 |
assert c.statistics().borrowers == ["someone"] |
| 96 |
|
| 97 |
c.release_on_behalf_of("someone") |
| 98 |
assert c.borrowed_tokens == 0 |
| 99 |
with assert_checkpoints(): |
| 100 |
async with c: |
| 101 |
assert c.borrowed_tokens == 1 |
| 102 |
|
| 103 |
async with _core.open_nursery() as nursery: |
| 104 |
await c.acquire_on_behalf_of("value 1") |
| 105 |
await c.acquire_on_behalf_of("value 2") |
| 106 |
nursery.start_soon(c.acquire_on_behalf_of, "value 3") |
| 107 |
await wait_all_tasks_blocked() |
| 108 |
assert c.borrowed_tokens == 2 |
| 109 |
assert c.statistics().tasks_waiting == 1 |
| 110 |
c.release_on_behalf_of("value 2") |
| 111 |
# Fairness: |
| 112 |
assert c.borrowed_tokens == 2 |
| 113 |
with pytest.raises(_core.WouldBlock): |
| 114 |
c.acquire_nowait() |
| 115 |
|
| 116 |
c.release_on_behalf_of("value 3") |
| 117 |
c.release_on_behalf_of("value 1") |
| 118 |
|
| 119 |
|
| 120 |
async def test_CapacityLimiter_inf() -> None: |
| 121 |
from math import inf |
| 122 |
|
| 123 |
c = CapacityLimiter(inf) |
| 124 |
repr(c) # smoke test |
| 125 |
assert c.total_tokens == inf |
| 126 |
assert c.borrowed_tokens == 0 |
| 127 |
assert c.available_tokens == inf |
| 128 |
with pytest.raises(RuntimeError): |
| 129 |
c.release() |
| 130 |
assert c.borrowed_tokens == 0 |
| 131 |
c.acquire_nowait() |
| 132 |
assert c.borrowed_tokens == 1 |
| 133 |
assert c.available_tokens == inf |
| 134 |
|
| 135 |
|
| 136 |
async def test_CapacityLimiter_change_total_tokens() -> None: |
| 137 |
c = CapacityLimiter(2) |
| 138 |
|
| 139 |
with pytest.raises(TypeError): |
| 140 |
c.total_tokens = 1.0 |
| 141 |
|
| 142 |
with pytest.raises(ValueError, match=r"^total_tokens must be >= 0$"): |
| 143 |
c.total_tokens = -1 |
| 144 |
|
| 145 |
with pytest.raises(ValueError, match=r"^total_tokens must be >= 0$"): |
| 146 |
c.total_tokens = -10 |
| 147 |
|
| 148 |
assert c.total_tokens == 2 |
| 149 |
|
| 150 |
async with _core.open_nursery() as nursery: |
| 151 |
for i in range(5): |
| 152 |
nursery.start_soon(c.acquire_on_behalf_of, i) |
| 153 |
await wait_all_tasks_blocked() |
| 154 |
assert set(c.statistics().borrowers) == {0, 1} |
| 155 |
assert c.statistics().tasks_waiting == 3 |
| 156 |
c.total_tokens += 2 |
| 157 |
assert set(c.statistics().borrowers) == {0, 1, 2, 3} |
| 158 |
assert c.statistics().tasks_waiting == 1 |
| 159 |
c.total_tokens -= 3 |
| 160 |
assert c.borrowed_tokens == 4 |
| 161 |
assert c.total_tokens == 1 |
| 162 |
c.release_on_behalf_of(0) |
| 163 |
c.release_on_behalf_of(1) |
| 164 |
c.release_on_behalf_of(2) |
| 165 |
assert set(c.statistics().borrowers) == {3} |
| 166 |
assert c.statistics().tasks_waiting == 1 |
| 167 |
c.release_on_behalf_of(3) |
| 168 |
assert set(c.statistics().borrowers) == {4} |
| 169 |
assert c.statistics().tasks_waiting == 0 |
| 170 |
|
| 171 |
|
| 172 |
# regression test for issue #548 |
| 173 |
async def test_CapacityLimiter_memleak_548() -> None: |
| 174 |
limiter = CapacityLimiter(total_tokens=1) |
| 175 |
await limiter.acquire() |
| 176 |
|
| 177 |
async with _core.open_nursery() as n: |
| 178 |
n.start_soon(limiter.acquire) |
| 179 |
await wait_all_tasks_blocked() # give it a chance to run the task |
| 180 |
n.cancel_scope.cancel() |
| 181 |
|
| 182 |
# if this is 1, the acquire call (despite being killed) is still there in the task, and will |
| 183 |
# leak memory all the while the limiter is active |
| 184 |
assert len(limiter._pending_borrowers) == 0 |
| 185 |
|
| 186 |
|
| 187 |
async def test_CapacityLimiter_zero_limit_tokens() -> None: |
| 188 |
c = CapacityLimiter(5) |
| 189 |
|
| 190 |
assert c.total_tokens == 5 |
| 191 |
|
| 192 |
async with _core.open_nursery() as nursery: |
| 193 |
c.total_tokens = 0 |
| 194 |
|
| 195 |
for i in range(5): |
| 196 |
nursery.start_soon(c.acquire_on_behalf_of, i) |
| 197 |
await wait_all_tasks_blocked() |
| 198 |
|
| 199 |
assert set(c.statistics().borrowers) == set() |
| 200 |
assert c.statistics().tasks_waiting == 5 |
| 201 |
|
| 202 |
c.total_tokens = 5 |
| 203 |
|
| 204 |
assert set(c.statistics().borrowers) == {0, 1, 2, 3, 4} |
| 205 |
|
| 206 |
nursery.start_soon(c.acquire_on_behalf_of, 5) |
| 207 |
await wait_all_tasks_blocked() |
| 208 |
|
| 209 |
assert c.statistics().tasks_waiting == 1 |
| 210 |
|
| 211 |
for i in range(5): |
| 212 |
c.release_on_behalf_of(i) |
| 213 |
|
| 214 |
assert c.statistics().tasks_waiting == 0 |
| 215 |
c.release_on_behalf_of(5) |
| 216 |
|
| 217 |
# making sure that zero limit capacity limiter doesn't let any tasks through |
| 218 |
|
| 219 |
c.total_tokens = 0 |
| 220 |
|
| 221 |
with pytest.raises(_core.WouldBlock): |
| 222 |
c.acquire_nowait() |
| 223 |
|
| 224 |
nursery.start_soon(c.acquire_on_behalf_of, 6) |
| 225 |
await wait_all_tasks_blocked() |
| 226 |
|
| 227 |
assert c.statistics().tasks_waiting == 1 |
| 228 |
assert c.statistics().borrowers == [] |
| 229 |
|
| 230 |
c.total_tokens = 1 |
| 231 |
assert c.statistics().tasks_waiting == 0 |
| 232 |
assert c.statistics().borrowers == [6] |
| 233 |
c.release_on_behalf_of(6) |
| 234 |
|
| 235 |
await c.acquire_on_behalf_of(0) # total_tokens is 1 |
| 236 |
|
| 237 |
nursery.start_soon(c.acquire_on_behalf_of, 1) |
| 238 |
await wait_all_tasks_blocked() |
| 239 |
c.total_tokens = 0 |
| 240 |
|
| 241 |
assert c.statistics().borrowers == [0] |
| 242 |
|
| 243 |
c.release_on_behalf_of(0) |
| 244 |
await wait_all_tasks_blocked() |
| 245 |
assert c.statistics().borrowers == [] |
| 246 |
assert c.statistics().tasks_waiting == 1 |
| 247 |
|
| 248 |
c.total_tokens = 1 |
| 249 |
await wait_all_tasks_blocked() |
| 250 |
assert c.statistics().borrowers == [1] |
| 251 |
assert c.statistics().tasks_waiting == 0 |
| 252 |
|
| 253 |
c.release_on_behalf_of(1) |
| 254 |
|
| 255 |
c.total_tokens = 0 |
| 256 |
|
| 257 |
nursery.cancel_scope.cancel() |
| 258 |
|
| 259 |
assert c.total_tokens == 0 |
| 260 |
assert c.statistics().borrowers == [] |
| 261 |
assert c._pending_borrowers == {} |
| 262 |
|
| 263 |
|
| 264 |
async def test_Semaphore() -> None: |
| 265 |
with pytest.raises(TypeError): |
| 266 |
Semaphore(1.0) # type: ignore[arg-type] |
| 267 |
with pytest.raises(ValueError, match=r"^initial value must be >= 0$"): |
| 268 |
Semaphore(-1) |
| 269 |
s = Semaphore(1) |
| 270 |
repr(s) # smoke test |
| 271 |
assert s.value == 1 |
| 272 |
assert s.max_value is None |
| 273 |
s.release() |
| 274 |
assert s.value == 2 |
| 275 |
assert s.statistics().tasks_waiting == 0 |
| 276 |
s.acquire_nowait() |
| 277 |
assert s.value == 1 |
| 278 |
with assert_checkpoints(): |
| 279 |
await s.acquire() |
| 280 |
assert s.value == 0 |
| 281 |
with pytest.raises(_core.WouldBlock): |
| 282 |
s.acquire_nowait() |
| 283 |
|
| 284 |
s.release() |
| 285 |
assert s.value == 1 |
| 286 |
with assert_checkpoints(): |
| 287 |
async with s: |
| 288 |
assert s.value == 0 |
| 289 |
assert s.value == 1 |
| 290 |
s.acquire_nowait() |
| 291 |
|
| 292 |
record = [] |
| 293 |
|
| 294 |
async def do_acquire(s: Semaphore) -> None: |
| 295 |
record.append("started") |
| 296 |
await s.acquire() |
| 297 |
record.append("finished") |
| 298 |
|
| 299 |
async with _core.open_nursery() as nursery: |
| 300 |
nursery.start_soon(do_acquire, s) |
| 301 |
await wait_all_tasks_blocked() |
| 302 |
assert record == ["started"] |
| 303 |
assert s.value == 0 |
| 304 |
s.release() |
| 305 |
# Fairness: |
| 306 |
assert s.value == 0 |
| 307 |
with pytest.raises(_core.WouldBlock): |
| 308 |
s.acquire_nowait() |
| 309 |
assert record == ["started", "finished"] |
| 310 |
|
| 311 |
|
| 312 |
def test_Semaphore_bounded() -> None: |
| 313 |
with pytest.raises(TypeError): |
| 314 |
Semaphore(1, max_value=1.0) # type: ignore[arg-type] |
| 315 |
with pytest.raises(ValueError, match=r"^max_values must be >= initial_value$"): |
| 316 |
Semaphore(2, max_value=1) |
| 317 |
bs = Semaphore(1, max_value=1) |
| 318 |
assert bs.max_value == 1 |
| 319 |
repr(bs) # smoke test |
| 320 |
with pytest.raises(ValueError, match=r"^semaphore released too many times$"): |
| 321 |
bs.release() |
| 322 |
assert bs.value == 1 |
| 323 |
bs.acquire_nowait() |
| 324 |
assert bs.value == 0 |
| 325 |
bs.release() |
| 326 |
assert bs.value == 1 |
| 327 |
|
| 328 |
|
| 329 |
@pytest.mark.parametrize("lockcls", [Lock, StrictFIFOLock], ids=lambda fn: fn.__name__) |
| 330 |
async def test_Lock_and_StrictFIFOLock( |
| 331 |
lockcls: type[Lock | StrictFIFOLock], |
| 332 |
) -> None: |
| 333 |
l = lockcls() # noqa |
| 334 |
assert not l.locked() |
| 335 |
|
| 336 |
# make sure locks can be weakref'ed (gh-331) |
| 337 |
r = weakref.ref(l) |
| 338 |
assert r() is l |
| 339 |
|
| 340 |
repr(l) # smoke test |
| 341 |
# make sure repr uses the right name for subclasses |
| 342 |
assert lockcls.__name__ in repr(l) |
| 343 |
with assert_checkpoints(): |
| 344 |
async with l: |
| 345 |
assert l.locked() |
| 346 |
repr(l) # smoke test (repr branches on locked/unlocked) |
| 347 |
assert not l.locked() |
| 348 |
l.acquire_nowait() |
| 349 |
assert l.locked() |
| 350 |
l.release() |
| 351 |
assert not l.locked() |
| 352 |
with assert_checkpoints(): |
| 353 |
await l.acquire() |
| 354 |
assert l.locked() |
| 355 |
l.release() |
| 356 |
assert not l.locked() |
| 357 |
|
| 358 |
l.acquire_nowait() |
| 359 |
with pytest.raises(RuntimeError): |
| 360 |
# Error out if we already own the lock |
| 361 |
l.acquire_nowait() |
| 362 |
l.release() |
| 363 |
with pytest.raises(RuntimeError): |
| 364 |
# Error out if we don't own the lock |
| 365 |
l.release() |
| 366 |
|
| 367 |
holder_task = None |
| 368 |
|
| 369 |
async def holder() -> None: |
| 370 |
nonlocal holder_task |
| 371 |
holder_task = _core.current_task() |
| 372 |
async with l: |
| 373 |
await sleep_forever() |
| 374 |
|
| 375 |
async with _core.open_nursery() as nursery: |
| 376 |
assert not l.locked() |
| 377 |
nursery.start_soon(holder) |
| 378 |
await wait_all_tasks_blocked() |
| 379 |
assert l.locked() |
| 380 |
# WouldBlock if someone else holds the lock |
| 381 |
with pytest.raises(_core.WouldBlock): |
| 382 |
l.acquire_nowait() |
| 383 |
# Can't release a lock someone else holds |
| 384 |
with pytest.raises(RuntimeError): |
| 385 |
l.release() |
| 386 |
|
| 387 |
statistics = l.statistics() |
| 388 |
print(statistics) |
| 389 |
assert statistics.locked |
| 390 |
assert statistics.owner is holder_task |
| 391 |
assert statistics.tasks_waiting == 0 |
| 392 |
|
| 393 |
nursery.start_soon(holder) |
| 394 |
await wait_all_tasks_blocked() |
| 395 |
statistics = l.statistics() |
| 396 |
print(statistics) |
| 397 |
assert statistics.tasks_waiting == 1 |
| 398 |
|
| 399 |
nursery.cancel_scope.cancel() |
| 400 |
|
| 401 |
statistics = l.statistics() |
| 402 |
assert not statistics.locked |
| 403 |
assert statistics.owner is None |
| 404 |
assert statistics.tasks_waiting == 0 |
| 405 |
|
| 406 |
|
| 407 |
async def test_Condition() -> None: |
| 408 |
with pytest.raises(TypeError): |
| 409 |
Condition(Semaphore(1)) # type: ignore[arg-type] |
| 410 |
with pytest.raises(TypeError): |
| 411 |
Condition(StrictFIFOLock) # type: ignore[arg-type] |
| 412 |
l = Lock() # noqa |
| 413 |
c = Condition(l) |
| 414 |
assert not l.locked() |
| 415 |
assert not c.locked() |
| 416 |
with assert_checkpoints(): |
| 417 |
await c.acquire() |
| 418 |
assert l.locked() |
| 419 |
assert c.locked() |
| 420 |
|
| 421 |
c = Condition() |
| 422 |
assert not c.locked() |
| 423 |
c.acquire_nowait() |
| 424 |
assert c.locked() |
| 425 |
with pytest.raises(RuntimeError): |
| 426 |
c.acquire_nowait() |
| 427 |
c.release() |
| 428 |
|
| 429 |
with pytest.raises(RuntimeError): |
| 430 |
# Can't wait without holding the lock |
| 431 |
await c.wait() |
| 432 |
with pytest.raises(RuntimeError): |
| 433 |
# Can't notify without holding the lock |
| 434 |
c.notify() |
| 435 |
with pytest.raises(RuntimeError): |
| 436 |
# Can't notify without holding the lock |
| 437 |
c.notify_all() |
| 438 |
|
| 439 |
finished_waiters = set() |
| 440 |
|
| 441 |
async def waiter(i: int) -> None: |
| 442 |
async with c: |
| 443 |
await c.wait() |
| 444 |
finished_waiters.add(i) |
| 445 |
|
| 446 |
async with _core.open_nursery() as nursery: |
| 447 |
for i in range(3): |
| 448 |
nursery.start_soon(waiter, i) |
| 449 |
await wait_all_tasks_blocked() |
| 450 |
async with c: |
| 451 |
c.notify() |
| 452 |
assert c.locked() |
| 453 |
await wait_all_tasks_blocked() |
| 454 |
assert finished_waiters == {0} |
| 455 |
async with c: |
| 456 |
c.notify_all() |
| 457 |
await wait_all_tasks_blocked() |
| 458 |
assert finished_waiters == {0, 1, 2} |
| 459 |
|
| 460 |
finished_waiters = set() |
| 461 |
async with _core.open_nursery() as nursery: |
| 462 |
for i in range(3): |
| 463 |
nursery.start_soon(waiter, i) |
| 464 |
await wait_all_tasks_blocked() |
| 465 |
async with c: |
| 466 |
c.notify(2) |
| 467 |
statistics = c.statistics() |
| 468 |
print(statistics) |
| 469 |
assert statistics.tasks_waiting == 1 |
| 470 |
assert statistics.lock_statistics.tasks_waiting == 2 |
| 471 |
# exiting the context manager hands off the lock to the first task |
| 472 |
assert c.statistics().lock_statistics.tasks_waiting == 1 |
| 473 |
|
| 474 |
await wait_all_tasks_blocked() |
| 475 |
assert finished_waiters == {0, 1} |
| 476 |
|
| 477 |
async with c: |
| 478 |
c.notify_all() |
| 479 |
|
| 480 |
# After being cancelled still hold the lock (!) |
| 481 |
# (Note that c.__aexit__ checks that we hold the lock as well) |
| 482 |
with _core.CancelScope() as scope: |
| 483 |
async with c: |
| 484 |
scope.cancel() |
| 485 |
try: |
| 486 |
await c.wait() |
| 487 |
finally: |
| 488 |
assert c.locked() |
| 489 |
|
| 490 |
|
| 491 |
from .._channel import open_memory_channel |
| 492 |
from .._sync import AsyncContextManagerMixin |
| 493 |
|
| 494 |
# Three ways of implementing a Lock in terms of a channel. Used to let us put |
| 495 |
# the channel through the generic lock tests. |
| 496 |
|
| 497 |
|
| 498 |
class ChannelLock1(AsyncContextManagerMixin): |
| 499 |
def __init__(self, capacity: int) -> None: |
| 500 |
self.s, self.r = open_memory_channel[None](capacity) |
| 501 |
for _ in range(capacity - 1): |
| 502 |
self.s.send_nowait(None) |
| 503 |
|
| 504 |
def acquire_nowait(self) -> None: |
| 505 |
self.s.send_nowait(None) |
| 506 |
|
| 507 |
async def acquire(self) -> None: |
| 508 |
await self.s.send(None) |
| 509 |
|
| 510 |
def release(self) -> None: |
| 511 |
self.r.receive_nowait() |
| 512 |
|
| 513 |
|
| 514 |
class ChannelLock2(AsyncContextManagerMixin): |
| 515 |
def __init__(self) -> None: |
| 516 |
self.s, self.r = open_memory_channel[None](10) |
| 517 |
self.s.send_nowait(None) |
| 518 |
|
| 519 |
def acquire_nowait(self) -> None: |
| 520 |
self.r.receive_nowait() |
| 521 |
|
| 522 |
async def acquire(self) -> None: |
| 523 |
await self.r.receive() |
| 524 |
|
| 525 |
def release(self) -> None: |
| 526 |
self.s.send_nowait(None) |
| 527 |
|
| 528 |
|
| 529 |
class ChannelLock3(AsyncContextManagerMixin): |
| 530 |
def __init__(self) -> None: |
| 531 |
self.s, self.r = open_memory_channel[None](0) |
| 532 |
# self.acquired is true when one task acquires the lock and |
| 533 |
# only becomes false when it's released and no tasks are |
| 534 |
# waiting to acquire. |
| 535 |
self.acquired = False |
| 536 |
|
| 537 |
def acquire_nowait(self) -> None: |
| 538 |
assert not self.acquired |
| 539 |
self.acquired = True |
| 540 |
|
| 541 |
async def acquire(self) -> None: |
| 542 |
if self.acquired: |
| 543 |
await self.s.send(None) |
| 544 |
else: |
| 545 |
self.acquired = True |
| 546 |
await _core.checkpoint() |
| 547 |
|
| 548 |
def release(self) -> None: |
| 549 |
try: |
| 550 |
self.r.receive_nowait() |
| 551 |
except _core.WouldBlock: |
| 552 |
assert self.acquired |
| 553 |
self.acquired = False |
| 554 |
|
| 555 |
|
| 556 |
lock_factories = [ |
| 557 |
lambda: CapacityLimiter(1), |
| 558 |
lambda: Semaphore(1), |
| 559 |
Lock, |
| 560 |
StrictFIFOLock, |
| 561 |
lambda: ChannelLock1(10), |
| 562 |
lambda: ChannelLock1(1), |
| 563 |
ChannelLock2, |
| 564 |
ChannelLock3, |
| 565 |
] |
| 566 |
lock_factory_names = [ |
| 567 |
"CapacityLimiter(1)", |
| 568 |
"Semaphore(1)", |
| 569 |
"Lock", |
| 570 |
"StrictFIFOLock", |
| 571 |
"ChannelLock1(10)", |
| 572 |
"ChannelLock1(1)", |
| 573 |
"ChannelLock2", |
| 574 |
"ChannelLock3", |
| 575 |
] |
| 576 |
|
| 577 |
generic_lock_test = pytest.mark.parametrize( |
| 578 |
"lock_factory", |
| 579 |
lock_factories, |
| 580 |
ids=lock_factory_names, |
| 581 |
) |
| 582 |
|
| 583 |
LockLike: TypeAlias = ( |
| 584 |
CapacityLimiter |
| 585 |
| Semaphore |
| 586 |
| Lock |
| 587 |
| StrictFIFOLock |
| 588 |
| ChannelLock1 |
| 589 |
| ChannelLock2 |
| 590 |
| ChannelLock3 |
| 591 |
) |
| 592 |
LockFactory: TypeAlias = Callable[[], LockLike] |
| 593 |
|
| 594 |
|
| 595 |
# Spawn a bunch of workers that take a lock and then yield; make sure that |
| 596 |
# only one worker is ever in the critical section at a time. |
| 597 |
@generic_lock_test |
| 598 |
async def test_generic_lock_exclusion(lock_factory: LockFactory) -> None: |
| 599 |
LOOPS = 10 |
| 600 |
WORKERS = 5 |
| 601 |
in_critical_section = False |
| 602 |
acquires = 0 |
| 603 |
|
| 604 |
async def worker(lock_like: LockLike) -> None: |
| 605 |
nonlocal in_critical_section, acquires |
| 606 |
for _ in range(LOOPS): |
| 607 |
async with lock_like: |
| 608 |
acquires += 1 |
| 609 |
assert not in_critical_section |
| 610 |
in_critical_section = True |
| 611 |
await _core.checkpoint() |
| 612 |
await _core.checkpoint() |
| 613 |
assert in_critical_section |
| 614 |
in_critical_section = False |
| 615 |
|
| 616 |
async with _core.open_nursery() as nursery: |
| 617 |
lock_like = lock_factory() |
| 618 |
for _ in range(WORKERS): |
| 619 |
nursery.start_soon(worker, lock_like) |
| 620 |
assert not in_critical_section |
| 621 |
assert acquires == LOOPS * WORKERS |
| 622 |
|
| 623 |
|
| 624 |
# Several workers queue on the same lock; make sure they each get it, in |
| 625 |
# order. |
| 626 |
@generic_lock_test |
| 627 |
async def test_generic_lock_fifo_fairness(lock_factory: LockFactory) -> None: |
| 628 |
initial_order = [] |
| 629 |
record = [] |
| 630 |
LOOPS = 5 |
| 631 |
|
| 632 |
async def loopy(name: int, lock_like: LockLike) -> None: |
| 633 |
# Record the order each task was initially scheduled in |
| 634 |
initial_order.append(name) |
| 635 |
for _ in range(LOOPS): |
| 636 |
async with lock_like: |
| 637 |
record.append(name) |
| 638 |
|
| 639 |
lock_like = lock_factory() |
| 640 |
async with _core.open_nursery() as nursery: |
| 641 |
nursery.start_soon(loopy, 1, lock_like) |
| 642 |
nursery.start_soon(loopy, 2, lock_like) |
| 643 |
nursery.start_soon(loopy, 3, lock_like) |
| 644 |
# The first three could be in any order due to scheduling randomness, |
| 645 |
# but after that they should repeat in the same order |
| 646 |
for i in range(LOOPS): |
| 647 |
assert record[3 * i : 3 * (i + 1)] == initial_order |
| 648 |
|
| 649 |
|
| 650 |
@generic_lock_test |
| 651 |
async def test_generic_lock_acquire_nowait_blocks_acquire( |
| 652 |
lock_factory: LockFactory, |
| 653 |
) -> None: |
| 654 |
lock_like = lock_factory() |
| 655 |
|
| 656 |
record = [] |
| 657 |
|
| 658 |
async def lock_taker() -> None: |
| 659 |
record.append("started") |
| 660 |
async with lock_like: |
| 661 |
pass |
| 662 |
record.append("finished") |
| 663 |
|
| 664 |
async with _core.open_nursery() as nursery: |
| 665 |
lock_like.acquire_nowait() |
| 666 |
nursery.start_soon(lock_taker) |
| 667 |
await wait_all_tasks_blocked() |
| 668 |
assert record == ["started"] |
| 669 |
lock_like.release() |
| 670 |
|
| 671 |
|
| 672 |
async def test_lock_acquire_unowned_lock() -> None: |
| 673 |
"""Test that trying to acquire a lock whose owner has exited raises an error. |
| 674 |
see https://github.com/python-trio/trio/issues/3035 |
| 675 |
""" |
| 676 |
assert not GLOBAL_PARKING_LOT_BREAKER |
| 677 |
lock = trio.Lock() |
| 678 |
async with trio.open_nursery() as nursery: |
| 679 |
nursery.start_soon(lock.acquire) |
| 680 |
owner_str = re.escape(str(lock._lot.broken_by[0])) |
| 681 |
with pytest.raises( |
| 682 |
trio.BrokenResourceError, |
| 683 |
match=f"^Owner of this lock exited without releasing: {owner_str}$", |
| 684 |
): |
| 685 |
await lock.acquire() |
| 686 |
assert not GLOBAL_PARKING_LOT_BREAKER |
| 687 |
|
| 688 |
|
| 689 |
async def test_lock_multiple_acquire() -> None: |
| 690 |
"""Test for error if awaiting on a lock whose owner exits without releasing. |
| 691 |
see https://github.com/python-trio/trio/issues/3035""" |
| 692 |
assert not GLOBAL_PARKING_LOT_BREAKER |
| 693 |
lock = trio.Lock() |
| 694 |
with pytest.RaisesGroup( |
| 695 |
pytest.RaisesExc( |
| 696 |
trio.BrokenResourceError, |
| 697 |
match="^Owner of this lock exited without releasing: ", |
| 698 |
), |
| 699 |
): |
| 700 |
async with trio.open_nursery() as nursery: |
| 701 |
nursery.start_soon(lock.acquire) |
| 702 |
nursery.start_soon(lock.acquire) |
| 703 |
assert not GLOBAL_PARKING_LOT_BREAKER |
| 704 |
|
| 705 |
|
| 706 |
async def test_lock_handover() -> None: |
| 707 |
assert not GLOBAL_PARKING_LOT_BREAKER |
| 708 |
child_task: Task | None = None |
| 709 |
lock = trio.Lock() |
| 710 |
|
| 711 |
# this task acquires the lock |
| 712 |
lock.acquire_nowait() |
| 713 |
assert { |
| 714 |
_core.current_task(): [ |
| 715 |
lock._lot, |
| 716 |
], |
| 717 |
} == GLOBAL_PARKING_LOT_BREAKER |
| 718 |
|
| 719 |
async with trio.open_nursery() as nursery: |
| 720 |
nursery.start_soon(lock.acquire) |
| 721 |
await wait_all_tasks_blocked() |
| 722 |
|
| 723 |
# hand over the lock to the child task |
| 724 |
lock.release() |
| 725 |
|
| 726 |
# check values, and get the identifier out of the dict for later check |
| 727 |
assert len(GLOBAL_PARKING_LOT_BREAKER) == 1 |
| 728 |
child_task = next(iter(GLOBAL_PARKING_LOT_BREAKER)) |
| 729 |
assert GLOBAL_PARKING_LOT_BREAKER[child_task] == [lock._lot] |
| 730 |
|
| 731 |
assert lock._lot.broken_by == [child_task] |
| 732 |
assert not GLOBAL_PARKING_LOT_BREAKER |