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 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071 1072 1073 1074 1075 1076 1077 1078 1079 1080 1081 1082 1083 1084 1085 1086 1087 1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126 1127 1128 1129 1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144 1145 1146 1147 1148 1149 1150 1151 1152 1153 1154 1155 1156 1157 1158 1159 1160 1161 1162 1163 1164 1165 1166 1167 1168 1169 1170 1171 1172 1173 1174 1175 1176 1177 1178 1179 1180 1181 1182 1183 1184 1185 1186 1187 1188 1189 1190 1191 1192 1193 1194 1195 1196 1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221 1222 1223 1224 1225 1226 1227 1228 1229 1230 1231 1232 1233 1234 1235 1236 1237 1238 1239 1240 1241 1242 1243 1244 1245 1246 1247 1248 1249 1250 1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269 1270 1271 1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292 1293 1294 1295 1296 1297 1298 1299 1300 1301 1302 1303 1304 1305 1306 1307 1308 1309 1310 1311 1312 1313 1314 1315 1316 1317 1318 1319 1320 1321 1322 1323 1324 1325 1326 1327 1328 1329 1330 1331 1332 1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344 1345 1346 1347 1348 1349 1350 1351 1352 1353 1354 1355 1356 1357 1358 1359 1360 1361 1362 1363 1364 1365 1366 1367 1368 1369 1370 1371 1372 1373 1374 1375 1376 1377 1378 1379 1380 1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399 1400 1401 1402 1403 1404 1405 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459 1460 1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494 1495 1496 1497 1498 1499 1500 1501 1502 1503 1504 1505 1506 1507 1508 1509 1510 1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526 1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663 1664 1665 1666 1667 1668 1669 1670 1671 1672 1673 1674 1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706 1707 1708 1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825
|
"""Tests for locks.py"""
import unittest
from unittest import mock
import re
import asyncio
import collections
STR_RGX_REPR = (
r'^<(?P<class>.*?) object at (?P<address>.*?)'
r'\[(?P<extras>'
r'(set|unset|locked|unlocked|filling|draining|resetting|broken)'
r'(, value:\d)?'
r'(, waiters:\d+)?'
r'(, waiters:\d+\/\d+)?' # barrier
r')\]>\z'
)
RGX_REPR = re.compile(STR_RGX_REPR)
def tearDownModule():
asyncio.events._set_event_loop_policy(None)
class LockTests(unittest.IsolatedAsyncioTestCase):
async def test_repr(self):
lock = asyncio.Lock()
self.assertEndsWith(repr(lock), '[unlocked]>')
self.assertTrue(RGX_REPR.match(repr(lock)))
await lock.acquire()
self.assertEndsWith(repr(lock), '[locked]>')
self.assertTrue(RGX_REPR.match(repr(lock)))
async def test_lock(self):
lock = asyncio.Lock()
with self.assertRaisesRegex(
TypeError,
"'Lock' object can't be awaited"
):
await lock
self.assertFalse(lock.locked())
async def test_lock_doesnt_accept_loop_parameter(self):
primitives_cls = [
asyncio.Lock,
asyncio.Condition,
asyncio.Event,
asyncio.Semaphore,
asyncio.BoundedSemaphore,
]
loop = asyncio.get_running_loop()
for cls in primitives_cls:
with self.assertRaisesRegex(
TypeError,
rf"{cls.__name__}\.__init__\(\) got an unexpected "
rf"keyword argument 'loop'"
):
cls(loop=loop)
async def test_lock_by_with_statement(self):
primitives = [
asyncio.Lock(),
asyncio.Condition(),
asyncio.Semaphore(),
asyncio.BoundedSemaphore(),
]
for lock in primitives:
await asyncio.sleep(0.01)
self.assertFalse(lock.locked())
with self.assertRaisesRegex(
TypeError,
r"'\w+' object can't be awaited"
):
with await lock:
pass
self.assertFalse(lock.locked())
async def test_acquire(self):
lock = asyncio.Lock()
result = []
self.assertTrue(await lock.acquire())
async def c1(result):
if await lock.acquire():
result.append(1)
return True
async def c2(result):
if await lock.acquire():
result.append(2)
return True
async def c3(result):
if await lock.acquire():
result.append(3)
return True
t1 = asyncio.create_task(c1(result))
t2 = asyncio.create_task(c2(result))
await asyncio.sleep(0)
self.assertEqual([], result)
lock.release()
await asyncio.sleep(0)
self.assertEqual([1], result)
await asyncio.sleep(0)
self.assertEqual([1], result)
t3 = asyncio.create_task(c3(result))
lock.release()
await asyncio.sleep(0)
self.assertEqual([1, 2], result)
lock.release()
await asyncio.sleep(0)
self.assertEqual([1, 2, 3], result)
self.assertTrue(t1.done())
self.assertTrue(t1.result())
self.assertTrue(t2.done())
self.assertTrue(t2.result())
self.assertTrue(t3.done())
self.assertTrue(t3.result())
async def test_acquire_cancel(self):
lock = asyncio.Lock()
self.assertTrue(await lock.acquire())
task = asyncio.create_task(lock.acquire())
asyncio.get_running_loop().call_soon(task.cancel)
with self.assertRaises(asyncio.CancelledError):
await task
self.assertFalse(lock._waiters)
async def test_cancel_race(self):
# Several tasks:
# - A acquires the lock
# - B is blocked in acquire()
# - C is blocked in acquire()
#
# Now, concurrently:
# - B is cancelled
# - A releases the lock
#
# If B's waiter is marked cancelled but not yet removed from
# _waiters, A's release() call will crash when trying to set
# B's waiter; instead, it should move on to C's waiter.
# Setup: A has the lock, b and c are waiting.
lock = asyncio.Lock()
async def lockit(name, blocker):
await lock.acquire()
try:
if blocker is not None:
await blocker
finally:
lock.release()
fa = asyncio.get_running_loop().create_future()
ta = asyncio.create_task(lockit('A', fa))
await asyncio.sleep(0)
self.assertTrue(lock.locked())
tb = asyncio.create_task(lockit('B', None))
await asyncio.sleep(0)
self.assertEqual(len(lock._waiters), 1)
tc = asyncio.create_task(lockit('C', None))
await asyncio.sleep(0)
self.assertEqual(len(lock._waiters), 2)
# Create the race and check.
# Without the fix this failed at the last assert.
fa.set_result(None)
tb.cancel()
self.assertTrue(lock._waiters[0].cancelled())
await asyncio.sleep(0)
self.assertFalse(lock.locked())
self.assertTrue(ta.done())
self.assertTrue(tb.cancelled())
await tc
async def test_cancel_release_race(self):
# Issue 32734
# Acquire 4 locks, cancel second, release first
# and 2 locks are taken at once.
loop = asyncio.get_running_loop()
lock = asyncio.Lock()
lock_count = 0
call_count = 0
async def lockit():
nonlocal lock_count
nonlocal call_count
call_count += 1
await lock.acquire()
lock_count += 1
def trigger():
t1.cancel()
lock.release()
await lock.acquire()
t1 = asyncio.create_task(lockit())
t2 = asyncio.create_task(lockit())
t3 = asyncio.create_task(lockit())
# Start scheduled tasks
await asyncio.sleep(0)
loop.call_soon(trigger)
with self.assertRaises(asyncio.CancelledError):
# Wait for cancellation
await t1
# Make sure only one lock was taken
self.assertEqual(lock_count, 1)
# While 3 calls were made to lockit()
self.assertEqual(call_count, 3)
self.assertTrue(t1.cancelled() and t2.done())
# Cleanup the task that is stuck on acquire.
t3.cancel()
await asyncio.sleep(0)
self.assertTrue(t3.cancelled())
async def test_finished_waiter_cancelled(self):
lock = asyncio.Lock()
await lock.acquire()
self.assertTrue(lock.locked())
tb = asyncio.create_task(lock.acquire())
await asyncio.sleep(0)
self.assertEqual(len(lock._waiters), 1)
# Create a second waiter, wake up the first, and cancel it.
# Without the fix, the second was not woken up.
tc = asyncio.create_task(lock.acquire())
tb.cancel()
lock.release()
await asyncio.sleep(0)
self.assertTrue(lock.locked())
self.assertTrue(tb.cancelled())
# Cleanup
await tc
async def test_release_not_acquired(self):
lock = asyncio.Lock()
self.assertRaises(RuntimeError, lock.release)
async def test_release_no_waiters(self):
lock = asyncio.Lock()
await lock.acquire()
self.assertTrue(lock.locked())
lock.release()
self.assertFalse(lock.locked())
async def test_context_manager(self):
lock = asyncio.Lock()
self.assertFalse(lock.locked())
async with lock:
self.assertTrue(lock.locked())
self.assertFalse(lock.locked())
class EventTests(unittest.IsolatedAsyncioTestCase):
def test_repr(self):
ev = asyncio.Event()
self.assertEndsWith(repr(ev), '[unset]>')
match = RGX_REPR.match(repr(ev))
self.assertEqual(match.group('extras'), 'unset')
ev.set()
self.assertEndsWith(repr(ev), '[set]>')
self.assertTrue(RGX_REPR.match(repr(ev)))
ev._waiters.append(mock.Mock())
self.assertTrue('waiters:1' in repr(ev))
self.assertTrue(RGX_REPR.match(repr(ev)))
async def test_wait(self):
ev = asyncio.Event()
self.assertFalse(ev.is_set())
result = []
async def c1(result):
if await ev.wait():
result.append(1)
async def c2(result):
if await ev.wait():
result.append(2)
async def c3(result):
if await ev.wait():
result.append(3)
t1 = asyncio.create_task(c1(result))
t2 = asyncio.create_task(c2(result))
await asyncio.sleep(0)
self.assertEqual([], result)
t3 = asyncio.create_task(c3(result))
ev.set()
await asyncio.sleep(0)
self.assertEqual([3, 1, 2], result)
self.assertTrue(t1.done())
self.assertIsNone(t1.result())
self.assertTrue(t2.done())
self.assertIsNone(t2.result())
self.assertTrue(t3.done())
self.assertIsNone(t3.result())
async def test_wait_on_set(self):
ev = asyncio.Event()
ev.set()
res = await ev.wait()
self.assertTrue(res)
async def test_wait_cancel(self):
ev = asyncio.Event()
wait = asyncio.create_task(ev.wait())
asyncio.get_running_loop().call_soon(wait.cancel)
with self.assertRaises(asyncio.CancelledError):
await wait
self.assertFalse(ev._waiters)
async def test_clear(self):
ev = asyncio.Event()
self.assertFalse(ev.is_set())
ev.set()
self.assertTrue(ev.is_set())
ev.clear()
self.assertFalse(ev.is_set())
async def test_clear_with_waiters(self):
ev = asyncio.Event()
result = []
async def c1(result):
if await ev.wait():
result.append(1)
return True
t = asyncio.create_task(c1(result))
await asyncio.sleep(0)
self.assertEqual([], result)
ev.set()
ev.clear()
self.assertFalse(ev.is_set())
ev.set()
ev.set()
self.assertEqual(1, len(ev._waiters))
await asyncio.sleep(0)
self.assertEqual([1], result)
self.assertEqual(0, len(ev._waiters))
self.assertTrue(t.done())
self.assertTrue(t.result())
class ConditionTests(unittest.IsolatedAsyncioTestCase):
async def test_wait(self):
cond = asyncio.Condition()
result = []
async def c1(result):
await cond.acquire()
if await cond.wait():
result.append(1)
return True
async def c2(result):
await cond.acquire()
if await cond.wait():
result.append(2)
return True
async def c3(result):
await cond.acquire()
if await cond.wait():
result.append(3)
return True
t1 = asyncio.create_task(c1(result))
t2 = asyncio.create_task(c2(result))
t3 = asyncio.create_task(c3(result))
await asyncio.sleep(0)
self.assertEqual([], result)
self.assertFalse(cond.locked())
self.assertTrue(await cond.acquire())
cond.notify()
await asyncio.sleep(0)
self.assertEqual([], result)
self.assertTrue(cond.locked())
cond.release()
await asyncio.sleep(0)
self.assertEqual([1], result)
self.assertTrue(cond.locked())
cond.notify(2)
await asyncio.sleep(0)
self.assertEqual([1], result)
self.assertTrue(cond.locked())
cond.release()
await asyncio.sleep(0)
self.assertEqual([1, 2], result)
self.assertTrue(cond.locked())
cond.release()
await asyncio.sleep(0)
self.assertEqual([1, 2, 3], result)
self.assertTrue(cond.locked())
self.assertTrue(t1.done())
self.assertTrue(t1.result())
self.assertTrue(t2.done())
self.assertTrue(t2.result())
self.assertTrue(t3.done())
self.assertTrue(t3.result())
async def test_wait_cancel(self):
cond = asyncio.Condition()
await cond.acquire()
wait = asyncio.create_task(cond.wait())
asyncio.get_running_loop().call_soon(wait.cancel)
with self.assertRaises(asyncio.CancelledError):
await wait
self.assertFalse(cond._waiters)
self.assertTrue(cond.locked())
async def test_wait_cancel_contested(self):
cond = asyncio.Condition()
await cond.acquire()
self.assertTrue(cond.locked())
wait_task = asyncio.create_task(cond.wait())
await asyncio.sleep(0)
self.assertFalse(cond.locked())
# Notify, but contest the lock before cancelling
await cond.acquire()
self.assertTrue(cond.locked())
cond.notify()
asyncio.get_running_loop().call_soon(wait_task.cancel)
asyncio.get_running_loop().call_soon(cond.release)
try:
await wait_task
except asyncio.CancelledError:
# Should not happen, since no cancellation points
pass
self.assertTrue(cond.locked())
async def test_wait_cancel_after_notify(self):
# See bpo-32841
waited = False
cond = asyncio.Condition()
async def wait_on_cond():
nonlocal waited
async with cond:
waited = True # Make sure this area was reached
await cond.wait()
waiter = asyncio.create_task(wait_on_cond())
await asyncio.sleep(0) # Start waiting
await cond.acquire()
cond.notify()
await asyncio.sleep(0) # Get to acquire()
waiter.cancel()
await asyncio.sleep(0) # Activate cancellation
cond.release()
await asyncio.sleep(0) # Cancellation should occur
self.assertTrue(waiter.cancelled())
self.assertTrue(waited)
async def test_wait_unacquired(self):
cond = asyncio.Condition()
with self.assertRaises(RuntimeError):
await cond.wait()
async def test_wait_for(self):
cond = asyncio.Condition()
presult = False
def predicate():
return presult
result = []
async def c1(result):
await cond.acquire()
if await cond.wait_for(predicate):
result.append(1)
cond.release()
return True
t = asyncio.create_task(c1(result))
await asyncio.sleep(0)
self.assertEqual([], result)
await cond.acquire()
cond.notify()
cond.release()
await asyncio.sleep(0)
self.assertEqual([], result)
presult = True
await cond.acquire()
cond.notify()
cond.release()
await asyncio.sleep(0)
self.assertEqual([1], result)
self.assertTrue(t.done())
self.assertTrue(t.result())
async def test_wait_for_unacquired(self):
cond = asyncio.Condition()
# predicate can return true immediately
res = await cond.wait_for(lambda: [1, 2, 3])
self.assertEqual([1, 2, 3], res)
with self.assertRaises(RuntimeError):
await cond.wait_for(lambda: False)
async def test_notify(self):
cond = asyncio.Condition()
result = []
async def c1(result):
await cond.acquire()
if await cond.wait():
result.append(1)
cond.release()
return True
async def c2(result):
await cond.acquire()
if await cond.wait():
result.append(2)
cond.release()
return True
async def c3(result):
await cond.acquire()
if await cond.wait():
result.append(3)
cond.release()
return True
t1 = asyncio.create_task(c1(result))
t2 = asyncio.create_task(c2(result))
t3 = asyncio.create_task(c3(result))
await asyncio.sleep(0)
self.assertEqual([], result)
await cond.acquire()
cond.notify(1)
cond.release()
await asyncio.sleep(0)
self.assertEqual([1], result)
await cond.acquire()
cond.notify(1)
cond.notify(2048)
cond.release()
await asyncio.sleep(0)
self.assertEqual([1, 2, 3], result)
self.assertTrue(t1.done())
self.assertTrue(t1.result())
self.assertTrue(t2.done())
self.assertTrue(t2.result())
self.assertTrue(t3.done())
self.assertTrue(t3.result())
async def test_notify_all(self):
cond = asyncio.Condition()
result = []
async def c1(result):
await cond.acquire()
if await cond.wait():
result.append(1)
cond.release()
return True
async def c2(result):
await cond.acquire()
if await cond.wait():
result.append(2)
cond.release()
return True
t1 = asyncio.create_task(c1(result))
t2 = asyncio.create_task(c2(result))
await asyncio.sleep(0)
self.assertEqual([], result)
await cond.acquire()
cond.notify_all()
cond.release()
await asyncio.sleep(0)
self.assertEqual([1, 2], result)
self.assertTrue(t1.done())
self.assertTrue(t1.result())
self.assertTrue(t2.done())
self.assertTrue(t2.result())
def test_notify_unacquired(self):
cond = asyncio.Condition()
self.assertRaises(RuntimeError, cond.notify)
def test_notify_all_unacquired(self):
cond = asyncio.Condition()
self.assertRaises(RuntimeError, cond.notify_all)
async def test_repr(self):
cond = asyncio.Condition()
self.assertTrue('unlocked' in repr(cond))
self.assertTrue(RGX_REPR.match(repr(cond)))
await cond.acquire()
self.assertTrue('locked' in repr(cond))
cond._waiters.append(mock.Mock())
self.assertTrue('waiters:1' in repr(cond))
self.assertTrue(RGX_REPR.match(repr(cond)))
cond._waiters.append(mock.Mock())
self.assertTrue('waiters:2' in repr(cond))
self.assertTrue(RGX_REPR.match(repr(cond)))
async def test_context_manager(self):
cond = asyncio.Condition()
self.assertFalse(cond.locked())
async with cond:
self.assertTrue(cond.locked())
self.assertFalse(cond.locked())
async def test_explicit_lock(self):
async def f(lock=None, cond=None):
if lock is None:
lock = asyncio.Lock()
if cond is None:
cond = asyncio.Condition(lock)
self.assertIs(cond._lock, lock)
self.assertFalse(lock.locked())
self.assertFalse(cond.locked())
async with cond:
self.assertTrue(lock.locked())
self.assertTrue(cond.locked())
self.assertFalse(lock.locked())
self.assertFalse(cond.locked())
async with lock:
self.assertTrue(lock.locked())
self.assertTrue(cond.locked())
self.assertFalse(lock.locked())
self.assertFalse(cond.locked())
# All should work in the same way.
await f()
await f(asyncio.Lock())
lock = asyncio.Lock()
await f(lock, asyncio.Condition(lock))
async def test_ambiguous_loops(self):
loop = asyncio.new_event_loop()
self.addCleanup(loop.close)
async def wrong_loop_in_lock():
with self.assertRaises(TypeError):
asyncio.Lock(loop=loop) # actively disallowed since 3.10
lock = asyncio.Lock()
lock._loop = loop # use private API for testing
async with lock:
# acquired immediately via the fast-path
# without interaction with any event loop.
cond = asyncio.Condition(lock)
# cond.acquire() will trigger waiting on the lock
# and it will discover the event loop mismatch.
with self.assertRaisesRegex(
RuntimeError,
"is bound to a different event loop",
):
await cond.acquire()
async def wrong_loop_in_cond():
# Same analogy here with the condition's loop.
lock = asyncio.Lock()
async with lock:
with self.assertRaises(TypeError):
asyncio.Condition(lock, loop=loop)
cond = asyncio.Condition(lock)
cond._loop = loop
with self.assertRaisesRegex(
RuntimeError,
"is bound to a different event loop",
):
await cond.wait()
await wrong_loop_in_lock()
await wrong_loop_in_cond()
async def test_timeout_in_block(self):
condition = asyncio.Condition()
async with condition:
with self.assertRaises(asyncio.TimeoutError):
await asyncio.wait_for(condition.wait(), timeout=0.5)
async def test_cancelled_error_wakeup(self):
# Test that a cancelled error, received when awaiting wakeup,
# will be re-raised un-modified.
wake = False
raised = None
cond = asyncio.Condition()
async def func():
nonlocal raised
async with cond:
with self.assertRaises(asyncio.CancelledError) as err:
await cond.wait_for(lambda: wake)
raised = err.exception
raise raised
task = asyncio.create_task(func())
await asyncio.sleep(0)
# Task is waiting on the condition, cancel it there.
task.cancel(msg="foo")
with self.assertRaises(asyncio.CancelledError) as err:
await task
self.assertEqual(err.exception.args, ("foo",))
# We should have got the _same_ exception instance as the one
# originally raised.
self.assertIs(err.exception, raised)
async def test_cancelled_error_re_aquire(self):
# Test that a cancelled error, received when re-aquiring lock,
# will be re-raised un-modified.
wake = False
raised = None
cond = asyncio.Condition()
async def func():
nonlocal raised
async with cond:
with self.assertRaises(asyncio.CancelledError) as err:
await cond.wait_for(lambda: wake)
raised = err.exception
raise raised
task = asyncio.create_task(func())
await asyncio.sleep(0)
# Task is waiting on the condition
await cond.acquire()
wake = True
cond.notify()
await asyncio.sleep(0)
# Task is now trying to re-acquire the lock, cancel it there.
task.cancel(msg="foo")
cond.release()
with self.assertRaises(asyncio.CancelledError) as err:
await task
self.assertEqual(err.exception.args, ("foo",))
# We should have got the _same_ exception instance as the one
# originally raised.
self.assertIs(err.exception, raised)
async def test_cancelled_wakeup(self):
# Test that a task cancelled at the "same" time as it is woken
# up as part of a Condition.notify() does not result in a lost wakeup.
# This test simulates a cancel while the target task is awaiting initial
# wakeup on the wakeup queue.
condition = asyncio.Condition()
state = 0
async def consumer():
nonlocal state
async with condition:
while True:
await condition.wait_for(lambda: state != 0)
if state < 0:
return
state -= 1
# create two consumers
c = [asyncio.create_task(consumer()) for _ in range(2)]
# wait for them to settle
await asyncio.sleep(0)
async with condition:
# produce one item and wake up one
state += 1
condition.notify(1)
# Cancel it while it is awaiting to be run.
# This cancellation could come from the outside
c[0].cancel()
# now wait for the item to be consumed
# if it doesn't means that our "notify" didn"t take hold.
# because it raced with a cancel()
try:
async with asyncio.timeout(0.01):
await condition.wait_for(lambda: state == 0)
except TimeoutError:
pass
self.assertEqual(state, 0)
# clean up
state = -1
condition.notify_all()
await c[1]
async def test_cancelled_wakeup_relock(self):
# Test that a task cancelled at the "same" time as it is woken
# up as part of a Condition.notify() does not result in a lost wakeup.
# This test simulates a cancel while the target task is acquiring the lock
# again.
condition = asyncio.Condition()
state = 0
async def consumer():
nonlocal state
async with condition:
while True:
await condition.wait_for(lambda: state != 0)
if state < 0:
return
state -= 1
# create two consumers
c = [asyncio.create_task(consumer()) for _ in range(2)]
# wait for them to settle
await asyncio.sleep(0)
async with condition:
# produce one item and wake up one
state += 1
condition.notify(1)
# now we sleep for a bit. This allows the target task to wake up and
# settle on re-aquiring the lock
await asyncio.sleep(0)
# Cancel it while awaiting the lock
# This cancel could come the outside.
c[0].cancel()
# now wait for the item to be consumed
# if it doesn't means that our "notify" didn"t take hold.
# because it raced with a cancel()
try:
async with asyncio.timeout(0.01):
await condition.wait_for(lambda: state == 0)
except TimeoutError:
pass
self.assertEqual(state, 0)
# clean up
state = -1
condition.notify_all()
await c[1]
class SemaphoreTests(unittest.IsolatedAsyncioTestCase):
def test_initial_value_zero(self):
sem = asyncio.Semaphore(0)
self.assertTrue(sem.locked())
async def test_repr(self):
sem = asyncio.Semaphore()
self.assertEndsWith(repr(sem), '[unlocked, value:1]>')
self.assertTrue(RGX_REPR.match(repr(sem)))
await sem.acquire()
self.assertEndsWith(repr(sem), '[locked]>')
self.assertTrue('waiters' not in repr(sem))
self.assertTrue(RGX_REPR.match(repr(sem)))
if sem._waiters is None:
sem._waiters = collections.deque()
sem._waiters.append(mock.Mock())
self.assertTrue('waiters:1' in repr(sem))
self.assertTrue(RGX_REPR.match(repr(sem)))
sem._waiters.append(mock.Mock())
self.assertTrue('waiters:2' in repr(sem))
self.assertTrue(RGX_REPR.match(repr(sem)))
async def test_semaphore(self):
sem = asyncio.Semaphore()
self.assertEqual(1, sem._value)
with self.assertRaisesRegex(
TypeError,
"'Semaphore' object can't be awaited",
):
await sem
self.assertFalse(sem.locked())
self.assertEqual(1, sem._value)
def test_semaphore_value(self):
self.assertRaises(ValueError, asyncio.Semaphore, -1)
async def test_acquire(self):
sem = asyncio.Semaphore(3)
result = []
self.assertTrue(await sem.acquire())
self.assertTrue(await sem.acquire())
self.assertFalse(sem.locked())
async def c1(result):
await sem.acquire()
result.append(1)
return True
async def c2(result):
await sem.acquire()
result.append(2)
return True
async def c3(result):
await sem.acquire()
result.append(3)
return True
async def c4(result):
await sem.acquire()
result.append(4)
return True
t1 = asyncio.create_task(c1(result))
t2 = asyncio.create_task(c2(result))
t3 = asyncio.create_task(c3(result))
await asyncio.sleep(0)
self.assertEqual([1], result)
self.assertTrue(sem.locked())
self.assertEqual(2, len(sem._waiters))
self.assertEqual(0, sem._value)
t4 = asyncio.create_task(c4(result))
sem.release()
sem.release()
self.assertEqual(0, sem._value)
await asyncio.sleep(0)
self.assertEqual(0, sem._value)
self.assertEqual(3, len(result))
self.assertTrue(sem.locked())
self.assertEqual(1, len(sem._waiters))
self.assertEqual(0, sem._value)
self.assertTrue(t1.done())
self.assertTrue(t1.result())
race_tasks = [t2, t3, t4]
done_tasks = [t for t in race_tasks if t.done() and t.result()]
self.assertEqual(2, len(done_tasks))
# cleanup locked semaphore
sem.release()
await asyncio.gather(*race_tasks)
async def test_acquire_cancel(self):
sem = asyncio.Semaphore()
await sem.acquire()
acquire = asyncio.create_task(sem.acquire())
asyncio.get_running_loop().call_soon(acquire.cancel)
with self.assertRaises(asyncio.CancelledError):
await acquire
self.assertTrue((not sem._waiters) or
all(waiter.done() for waiter in sem._waiters))
async def test_acquire_cancel_before_awoken(self):
sem = asyncio.Semaphore(value=0)
t1 = asyncio.create_task(sem.acquire())
t2 = asyncio.create_task(sem.acquire())
t3 = asyncio.create_task(sem.acquire())
t4 = asyncio.create_task(sem.acquire())
await asyncio.sleep(0)
t1.cancel()
t2.cancel()
sem.release()
await asyncio.sleep(0)
await asyncio.sleep(0)
num_done = sum(t.done() for t in [t3, t4])
self.assertEqual(num_done, 1)
self.assertTrue(t3.done())
self.assertFalse(t4.done())
t3.cancel()
t4.cancel()
await asyncio.sleep(0)
async def test_acquire_hang(self):
sem = asyncio.Semaphore(value=0)
t1 = asyncio.create_task(sem.acquire())
t2 = asyncio.create_task(sem.acquire())
await asyncio.sleep(0)
t1.cancel()
sem.release()
await asyncio.sleep(0)
await asyncio.sleep(0)
self.assertTrue(sem.locked())
self.assertTrue(t2.done())
async def test_acquire_no_hang(self):
sem = asyncio.Semaphore(1)
async def c1():
async with sem:
await asyncio.sleep(0)
t2.cancel()
async def c2():
async with sem:
self.assertFalse(True)
t1 = asyncio.create_task(c1())
t2 = asyncio.create_task(c2())
r1, r2 = await asyncio.gather(t1, t2, return_exceptions=True)
self.assertTrue(r1 is None)
self.assertTrue(isinstance(r2, asyncio.CancelledError))
await asyncio.wait_for(sem.acquire(), timeout=1.0)
def test_release_not_acquired(self):
sem = asyncio.BoundedSemaphore()
self.assertRaises(ValueError, sem.release)
async def test_release_no_waiters(self):
sem = asyncio.Semaphore()
await sem.acquire()
self.assertTrue(sem.locked())
sem.release()
self.assertFalse(sem.locked())
async def test_acquire_fifo_order(self):
sem = asyncio.Semaphore(1)
result = []
async def coro(tag):
await sem.acquire()
result.append(f'{tag}_1')
await asyncio.sleep(0.01)
sem.release()
await sem.acquire()
result.append(f'{tag}_2')
await asyncio.sleep(0.01)
sem.release()
async with asyncio.TaskGroup() as tg:
tg.create_task(coro('c1'))
tg.create_task(coro('c2'))
tg.create_task(coro('c3'))
self.assertEqual(
['c1_1', 'c2_1', 'c3_1', 'c1_2', 'c2_2', 'c3_2'],
result
)
async def test_acquire_fifo_order_2(self):
sem = asyncio.Semaphore(1)
result = []
async def c1(result):
await sem.acquire()
result.append(1)
return True
async def c2(result):
await sem.acquire()
result.append(2)
sem.release()
await sem.acquire()
result.append(4)
return True
async def c3(result):
await sem.acquire()
result.append(3)
return True
t1 = asyncio.create_task(c1(result))
t2 = asyncio.create_task(c2(result))
t3 = asyncio.create_task(c3(result))
await asyncio.sleep(0)
sem.release()
sem.release()
tasks = [t1, t2, t3]
await asyncio.gather(*tasks)
self.assertEqual([1, 2, 3, 4], result)
async def test_acquire_fifo_order_3(self):
sem = asyncio.Semaphore(0)
result = []
async def c1(result):
await sem.acquire()
result.append(1)
return True
async def c2(result):
await sem.acquire()
result.append(2)
return True
async def c3(result):
await sem.acquire()
result.append(3)
return True
t1 = asyncio.create_task(c1(result))
t2 = asyncio.create_task(c2(result))
t3 = asyncio.create_task(c3(result))
await asyncio.sleep(0)
t1.cancel()
await asyncio.sleep(0)
sem.release()
sem.release()
tasks = [t1, t2, t3]
await asyncio.gather(*tasks, return_exceptions=True)
self.assertEqual([2, 3], result)
async def test_acquire_fifo_order_4(self):
# Test that a successful `acquire()` will wake up multiple Tasks
# that were waiting in the Semaphore queue due to FIFO rules.
sem = asyncio.Semaphore(0)
result = []
count = 0
async def c1(result):
# First task immediately waits for semaphore. It will be awoken by c2.
self.assertEqual(sem._value, 0)
await sem.acquire()
# We should have woken up all waiting tasks now.
self.assertEqual(sem._value, 0)
# Create a fourth task. It should run after c3, not c2.
nonlocal t4
t4 = asyncio.create_task(c4(result))
result.append(1)
return True
async def c2(result):
# The second task begins by releasing semaphore three times,
# for c1, c2, and c3.
sem.release()
sem.release()
sem.release()
self.assertEqual(sem._value, 2)
# It is locked, because c1 hasn't woken up yet.
self.assertTrue(sem.locked())
await sem.acquire()
result.append(2)
return True
async def c3(result):
await sem.acquire()
self.assertTrue(sem.locked())
result.append(3)
return True
async def c4(result):
result.append(4)
return True
t1 = asyncio.create_task(c1(result))
t2 = asyncio.create_task(c2(result))
t3 = asyncio.create_task(c3(result))
t4 = None
await asyncio.sleep(0)
# Three tasks are in the queue, the first hasn't woken up yet.
self.assertEqual(sem._value, 2)
self.assertEqual(len(sem._waiters), 3)
await asyncio.sleep(0)
tasks = [t1, t2, t3, t4]
await asyncio.gather(*tasks)
self.assertEqual([1, 2, 3, 4], result)
class BarrierTests(unittest.IsolatedAsyncioTestCase):
async def asyncSetUp(self):
await super().asyncSetUp()
self.N = 5
def make_tasks(self, n, coro):
tasks = [asyncio.create_task(coro()) for _ in range(n)]
return tasks
async def gather_tasks(self, n, coro):
tasks = self.make_tasks(n, coro)
res = await asyncio.gather(*tasks)
return res, tasks
async def test_barrier(self):
barrier = asyncio.Barrier(self.N)
self.assertIn("filling", repr(barrier))
with self.assertRaisesRegex(
TypeError,
"'Barrier' object can't be awaited",
):
await barrier
self.assertIn("filling", repr(barrier))
async def test_repr(self):
barrier = asyncio.Barrier(self.N)
self.assertTrue(RGX_REPR.match(repr(barrier)))
self.assertIn("filling", repr(barrier))
waiters = []
async def wait(barrier):
await barrier.wait()
incr = 2
for i in range(incr):
waiters.append(asyncio.create_task(wait(barrier)))
await asyncio.sleep(0)
self.assertTrue(RGX_REPR.match(repr(barrier)))
self.assertTrue(f"waiters:{incr}/{self.N}" in repr(barrier))
self.assertIn("filling", repr(barrier))
# create missing waiters
for i in range(barrier.parties - barrier.n_waiting):
waiters.append(asyncio.create_task(wait(barrier)))
await asyncio.sleep(0)
self.assertTrue(RGX_REPR.match(repr(barrier)))
self.assertIn("draining", repr(barrier))
# add a part of waiters
for i in range(incr):
waiters.append(asyncio.create_task(wait(barrier)))
await asyncio.sleep(0)
# and reset
await barrier.reset()
self.assertTrue(RGX_REPR.match(repr(barrier)))
self.assertIn("resetting", repr(barrier))
# add a part of waiters again
for i in range(incr):
waiters.append(asyncio.create_task(wait(barrier)))
await asyncio.sleep(0)
# and abort
await barrier.abort()
self.assertTrue(RGX_REPR.match(repr(barrier)))
self.assertIn("broken", repr(barrier))
self.assertTrue(barrier.broken)
# suppress unhandled exceptions
await asyncio.gather(*waiters, return_exceptions=True)
async def test_barrier_parties(self):
self.assertRaises(ValueError, lambda: asyncio.Barrier(0))
self.assertRaises(ValueError, lambda: asyncio.Barrier(-4))
self.assertIsInstance(asyncio.Barrier(self.N), asyncio.Barrier)
async def test_context_manager(self):
self.N = 3
barrier = asyncio.Barrier(self.N)
results = []
async def coro():
async with barrier as i:
results.append(i)
await self.gather_tasks(self.N, coro)
self.assertListEqual(sorted(results), list(range(self.N)))
self.assertEqual(barrier.n_waiting, 0)
self.assertFalse(barrier.broken)
async def test_filling_one_task(self):
barrier = asyncio.Barrier(1)
async def f():
async with barrier as i:
return True
ret = await f()
self.assertTrue(ret)
self.assertEqual(barrier.n_waiting, 0)
self.assertFalse(barrier.broken)
async def test_filling_one_task_twice(self):
barrier = asyncio.Barrier(1)
t1 = asyncio.create_task(barrier.wait())
await asyncio.sleep(0)
self.assertEqual(barrier.n_waiting, 0)
t2 = asyncio.create_task(barrier.wait())
await asyncio.sleep(0)
self.assertEqual(t1.result(), t2.result())
self.assertEqual(t1.done(), t2.done())
self.assertEqual(barrier.n_waiting, 0)
self.assertFalse(barrier.broken)
async def test_filling_task_by_task(self):
self.N = 3
barrier = asyncio.Barrier(self.N)
t1 = asyncio.create_task(barrier.wait())
await asyncio.sleep(0)
self.assertEqual(barrier.n_waiting, 1)
self.assertIn("filling", repr(barrier))
t2 = asyncio.create_task(barrier.wait())
await asyncio.sleep(0)
self.assertEqual(barrier.n_waiting, 2)
self.assertIn("filling", repr(barrier))
t3 = asyncio.create_task(barrier.wait())
await asyncio.sleep(0)
await asyncio.wait([t1, t2, t3])
self.assertEqual(barrier.n_waiting, 0)
self.assertFalse(barrier.broken)
async def test_filling_tasks_wait_twice(self):
barrier = asyncio.Barrier(self.N)
results = []
async def coro():
async with barrier:
results.append(True)
async with barrier:
results.append(False)
await self.gather_tasks(self.N, coro)
self.assertEqual(len(results), self.N*2)
self.assertEqual(results.count(True), self.N)
self.assertEqual(results.count(False), self.N)
self.assertEqual(barrier.n_waiting, 0)
self.assertFalse(barrier.broken)
async def test_filling_tasks_check_return_value(self):
barrier = asyncio.Barrier(self.N)
results1 = []
results2 = []
async def coro():
async with barrier:
results1.append(True)
async with barrier as i:
results2.append(True)
return i
res, _ = await self.gather_tasks(self.N, coro)
self.assertEqual(len(results1), self.N)
self.assertTrue(all(results1))
self.assertEqual(len(results2), self.N)
self.assertTrue(all(results2))
self.assertListEqual(sorted(res), list(range(self.N)))
self.assertEqual(barrier.n_waiting, 0)
self.assertFalse(barrier.broken)
async def test_draining_state(self):
barrier = asyncio.Barrier(self.N)
results = []
async def coro():
async with barrier:
# barrier state change to filling for the last task release
results.append("draining" in repr(barrier))
await self.gather_tasks(self.N, coro)
self.assertEqual(len(results), self.N)
self.assertEqual(results[-1], False)
self.assertTrue(all(results[:self.N-1]))
self.assertEqual(barrier.n_waiting, 0)
self.assertFalse(barrier.broken)
async def test_blocking_tasks_while_draining(self):
rewait = 2
barrier = asyncio.Barrier(self.N)
barrier_nowaiting = asyncio.Barrier(self.N - rewait)
results = []
rewait_n = rewait
counter = 0
async def coro():
nonlocal rewait_n
# first time waiting
await barrier.wait()
# after waiting once for all tasks
if rewait_n > 0:
rewait_n -= 1
# wait again only for rewait tasks
await barrier.wait()
else:
# wait for end of draining state
await barrier_nowaiting.wait()
# wait for other waiting tasks
await barrier.wait()
# a success means that barrier_nowaiting
# was waited for exactly N-rewait=3 times
await self.gather_tasks(self.N, coro)
async def test_filling_tasks_cancel_one(self):
self.N = 3
barrier = asyncio.Barrier(self.N)
results = []
async def coro():
await barrier.wait()
results.append(True)
t1 = asyncio.create_task(coro())
await asyncio.sleep(0)
self.assertEqual(barrier.n_waiting, 1)
t2 = asyncio.create_task(coro())
await asyncio.sleep(0)
self.assertEqual(barrier.n_waiting, 2)
t1.cancel()
await asyncio.sleep(0)
self.assertEqual(barrier.n_waiting, 1)
with self.assertRaises(asyncio.CancelledError):
await t1
self.assertTrue(t1.cancelled())
t3 = asyncio.create_task(coro())
await asyncio.sleep(0)
self.assertEqual(barrier.n_waiting, 2)
t4 = asyncio.create_task(coro())
await asyncio.gather(t2, t3, t4)
self.assertEqual(len(results), self.N)
self.assertTrue(all(results))
self.assertEqual(barrier.n_waiting, 0)
self.assertFalse(barrier.broken)
async def test_reset_barrier(self):
barrier = asyncio.Barrier(1)
asyncio.create_task(barrier.reset())
await asyncio.sleep(0)
self.assertEqual(barrier.n_waiting, 0)
self.assertFalse(barrier.broken)
async def test_reset_barrier_while_tasks_waiting(self):
barrier = asyncio.Barrier(self.N)
results = []
async def coro():
try:
await barrier.wait()
except asyncio.BrokenBarrierError:
results.append(True)
async def coro_reset():
await barrier.reset()
# N-1 tasks waiting on barrier with N parties
tasks = self.make_tasks(self.N-1, coro)
await asyncio.sleep(0)
# reset the barrier
asyncio.create_task(coro_reset())
await asyncio.gather(*tasks)
self.assertEqual(len(results), self.N-1)
self.assertTrue(all(results))
self.assertEqual(barrier.n_waiting, 0)
self.assertNotIn("resetting", repr(barrier))
self.assertFalse(barrier.broken)
async def test_reset_barrier_when_tasks_half_draining(self):
barrier = asyncio.Barrier(self.N)
results1 = []
rest_of_tasks = self.N//2
async def coro():
try:
await barrier.wait()
except asyncio.BrokenBarrierError:
# catch here waiting tasks
results1.append(True)
else:
# here drained task outside the barrier
if rest_of_tasks == barrier._count:
# tasks outside the barrier
await barrier.reset()
await self.gather_tasks(self.N, coro)
self.assertEqual(results1, [True]*rest_of_tasks)
self.assertEqual(barrier.n_waiting, 0)
self.assertNotIn("resetting", repr(barrier))
self.assertFalse(barrier.broken)
async def test_reset_barrier_when_tasks_half_draining_half_blocking(self):
barrier = asyncio.Barrier(self.N)
results1 = []
results2 = []
blocking_tasks = self.N//2
count = 0
async def coro():
nonlocal count
try:
await barrier.wait()
except asyncio.BrokenBarrierError:
# here catch still waiting tasks
results1.append(True)
# so now waiting again to reach nb_parties
await barrier.wait()
else:
count += 1
if count > blocking_tasks:
# reset now: raise asyncio.BrokenBarrierError for waiting tasks
await barrier.reset()
# so now waiting again to reach nb_parties
await barrier.wait()
else:
try:
await barrier.wait()
except asyncio.BrokenBarrierError:
# here no catch - blocked tasks go to wait
results2.append(True)
await self.gather_tasks(self.N, coro)
self.assertEqual(results1, [True]*blocking_tasks)
self.assertEqual(results2, [])
self.assertEqual(barrier.n_waiting, 0)
self.assertNotIn("resetting", repr(barrier))
self.assertFalse(barrier.broken)
async def test_reset_barrier_while_tasks_waiting_and_waiting_again(self):
barrier = asyncio.Barrier(self.N)
results1 = []
results2 = []
async def coro1():
try:
await barrier.wait()
except asyncio.BrokenBarrierError:
results1.append(True)
finally:
await barrier.wait()
results2.append(True)
async def coro2():
async with barrier:
results2.append(True)
tasks = self.make_tasks(self.N-1, coro1)
# reset barrier, N-1 waiting tasks raise an BrokenBarrierError
asyncio.create_task(barrier.reset())
await asyncio.sleep(0)
# complete waiting tasks in the `finally`
asyncio.create_task(coro2())
await asyncio.gather(*tasks)
self.assertFalse(barrier.broken)
self.assertEqual(len(results1), self.N-1)
self.assertTrue(all(results1))
self.assertEqual(len(results2), self.N)
self.assertTrue(all(results2))
self.assertEqual(barrier.n_waiting, 0)
async def test_reset_barrier_while_tasks_draining(self):
barrier = asyncio.Barrier(self.N)
results1 = []
results2 = []
results3 = []
count = 0
async def coro():
nonlocal count
i = await barrier.wait()
count += 1
if count == self.N:
# last task exited from barrier
await barrier.reset()
# wait here to reach the `parties`
await barrier.wait()
else:
try:
# second waiting
await barrier.wait()
# N-1 tasks here
results1.append(True)
except Exception as e:
# never goes here
results2.append(True)
# Now, pass the barrier again
# last wait, must be completed
k = await barrier.wait()
results3.append(True)
await self.gather_tasks(self.N, coro)
self.assertFalse(barrier.broken)
self.assertTrue(all(results1))
self.assertEqual(len(results1), self.N-1)
self.assertEqual(len(results2), 0)
self.assertEqual(len(results3), self.N)
self.assertTrue(all(results3))
self.assertEqual(barrier.n_waiting, 0)
async def test_abort_barrier(self):
barrier = asyncio.Barrier(1)
asyncio.create_task(barrier.abort())
await asyncio.sleep(0)
self.assertEqual(barrier.n_waiting, 0)
self.assertTrue(barrier.broken)
async def test_abort_barrier_when_tasks_half_draining_half_blocking(self):
barrier = asyncio.Barrier(self.N)
results1 = []
results2 = []
blocking_tasks = self.N//2
count = 0
async def coro():
nonlocal count
try:
await barrier.wait()
except asyncio.BrokenBarrierError:
# here catch tasks waiting to drain
results1.append(True)
else:
count += 1
if count > blocking_tasks:
# abort now: raise asyncio.BrokenBarrierError for all tasks
await barrier.abort()
else:
try:
await barrier.wait()
except asyncio.BrokenBarrierError:
# here catch blocked tasks (already drained)
results2.append(True)
await self.gather_tasks(self.N, coro)
self.assertTrue(barrier.broken)
self.assertEqual(results1, [True]*blocking_tasks)
self.assertEqual(results2, [True]*(self.N-blocking_tasks-1))
self.assertEqual(barrier.n_waiting, 0)
self.assertNotIn("resetting", repr(barrier))
async def test_abort_barrier_when_exception(self):
# test from threading.Barrier: see `lock_tests.test_reset`
barrier = asyncio.Barrier(self.N)
results1 = []
results2 = []
async def coro():
try:
async with barrier as i :
if i == self.N//2:
raise RuntimeError
async with barrier:
results1.append(True)
except asyncio.BrokenBarrierError:
results2.append(True)
except RuntimeError:
await barrier.abort()
await self.gather_tasks(self.N, coro)
self.assertTrue(barrier.broken)
self.assertEqual(len(results1), 0)
self.assertEqual(len(results2), self.N-1)
self.assertTrue(all(results2))
self.assertEqual(barrier.n_waiting, 0)
async def test_abort_barrier_when_exception_then_resetting(self):
# test from threading.Barrier: see `lock_tests.test_abort_and_reset`
barrier1 = asyncio.Barrier(self.N)
barrier2 = asyncio.Barrier(self.N)
results1 = []
results2 = []
results3 = []
async def coro():
try:
i = await barrier1.wait()
if i == self.N//2:
raise RuntimeError
await barrier1.wait()
results1.append(True)
except asyncio.BrokenBarrierError:
results2.append(True)
except RuntimeError:
await barrier1.abort()
# Synchronize and reset the barrier. Must synchronize first so
# that everyone has left it when we reset, and after so that no
# one enters it before the reset.
i = await barrier2.wait()
if i == self.N//2:
await barrier1.reset()
await barrier2.wait()
await barrier1.wait()
results3.append(True)
await self.gather_tasks(self.N, coro)
self.assertFalse(barrier1.broken)
self.assertEqual(len(results1), 0)
self.assertEqual(len(results2), self.N-1)
self.assertTrue(all(results2))
self.assertEqual(len(results3), self.N)
self.assertTrue(all(results3))
self.assertEqual(barrier1.n_waiting, 0)
if __name__ == '__main__':
unittest.main()
|