Skip to content

Commit caf3bbc

Browse files
allow switching multiple times
1 parent 85ff33d commit caf3bbc

File tree

3 files changed

+23
-5
lines changed

3 files changed

+23
-5
lines changed

docs/source/devel/testloop.rst

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,6 +27,12 @@ Async commands
2727

2828
.. autoclass:: Schedule(*await Any)
2929

30-
.. autoclass:: Switch
30+
.. py:class:: Switch(skip: int, /)
31+
:no-index:
32+
33+
.. py:class:: Switch(min: int, max: int, /)
34+
:no-index:
35+
36+
.. autoclass:: Switch()
3137

3238
.. autoclass:: Lock

unittests/test_itertools.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -322,8 +322,7 @@ async def test_tee_concurrent_locked():
322322
async def iter_values():
323323
for item in items:
324324
# switch to other tasks a few times to guarantees another runs
325-
for _ in range(5):
326-
await Switch()
325+
await Switch(5)
327326
yield item
328327

329328
async def test_peer(peer_tee):
@@ -354,8 +353,7 @@ async def test_tee_concurrent_unlocked():
354353
async def iter_values():
355354
for item in items:
356355
# switch to other tasks a few times to guarantee another runs
357-
for _ in range(5):
358-
await Switch()
356+
await Switch(5)
359357
yield item
360358

361359
async def test_peer(peer_tee):

unittests/utility.py

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@
1212
)
1313
from functools import wraps
1414
from collections import deque
15+
from random import randint
1516

1617

1718
T = TypeVar("T")
@@ -116,10 +117,23 @@ class Switch:
116117
all other runnable coroutines of the event loop.
117118
This is similar to the common ``sleep(0)`` function
118119
of regular event loop frameworks.
120+
121+
If a single argument is given, this specifies how many
122+
turns should be skipped. The default corresponds to `0`.
123+
If two arguments are given, this is interpreted as an
124+
inclusive interval to randomly select the skip count.
119125
"""
120126

127+
def __init__(self, skip: int = 0, limit: int = 0, /) -> None:
128+
if limit <= 0:
129+
self._idle_count = skip
130+
else:
131+
self._idle_count = randint(skip, limit)
132+
121133
def __await__(self):
122134
yield self
135+
for _ in range(self._idle_count):
136+
yield self
123137

124138

125139
class Lock:

0 commit comments

Comments
 (0)