File: asyncio.py

package info (click to toggle)
python-aioitertools 0.12.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 348 kB
  • sloc: python: 2,025; makefile: 49
file content (259 lines) | stat: -rw-r--r-- 7,752 bytes parent folder | download
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
# Copyright 2022 Amethyst Reese
# Licensed under the MIT license

import asyncio
from unittest import TestCase

import aioitertools as ait
import aioitertools.asyncio as aio
from .helpers import async_test

slist = ["A", "B", "C"]
srange = range(3)


class AsyncioTest(TestCase):
    def test_import(self):
        self.assertEqual(ait.asyncio, aio)

    @async_test
    async def test_as_completed(self):
        async def sleepy(number, duration):
            await asyncio.sleep(duration)
            return number

        pairs = [(1, 0.3), (2, 0.1), (3, 0.5)]
        expected = [2, 1, 3]

        futures = [sleepy(*pair) for pair in pairs]
        results = await ait.list(aio.as_completed(futures))
        self.assertEqual(results, expected)

        futures = [sleepy(*pair) for pair in pairs]
        results = []
        async for value in aio.as_completed(futures):
            results.append(value)
        self.assertEqual(results, expected)

    @async_test
    async def test_as_completed_timeout(self):
        calls = [(1.0,), (0.1,)]

        futures = [asyncio.sleep(*args) for args in calls]
        with self.assertRaises(asyncio.TimeoutError):
            await ait.list(aio.as_completed(futures, timeout=0.5))

        futures = [asyncio.sleep(*args) for args in calls]
        results = 0
        with self.assertRaises(asyncio.TimeoutError):
            async for _ in aio.as_completed(futures, timeout=0.5):
                results += 1
        self.assertEqual(results, 1)

    @async_test
    async def test_as_generated(self):
        async def gen():
            for i in range(10):
                yield i
                await asyncio.sleep(0)

        gens = [gen(), gen(), gen()]
        expected = list(range(10)) * 3
        results = []
        async for value in aio.as_generated(gens):
            results.append(value)
        self.assertEqual(30, len(results))
        self.assertListEqual(sorted(expected), sorted(results))

    @async_test
    async def test_as_generated_exception(self):
        async def gen1():
            for i in range(3):
                yield i
                await asyncio.sleep(0)
            raise Exception("fake")

        async def gen2():
            for i in range(10):
                yield i
                await asyncio.sleep(0)

        gens = [gen1(), gen2()]
        results = []
        with self.assertRaisesRegex(Exception, "fake"):
            async for value in aio.as_generated(gens):
                results.append(value)
        self.assertNotIn(10, results)

    @async_test
    async def test_as_generated_return_exception(self):
        async def gen1():
            for i in range(3):
                yield i
                await asyncio.sleep(0)
            raise Exception("fake")

        async def gen2():
            for i in range(10):
                yield i
                await asyncio.sleep(0)

        gens = [gen1(), gen2()]
        expected = list(range(3)) + list(range(10))
        errors = []
        results = []
        async for value in aio.as_generated(gens, return_exceptions=True):
            if isinstance(value, Exception):
                errors.append(value)
            else:
                results.append(value)
        self.assertListEqual(sorted(expected), sorted(results))
        self.assertEqual(1, len(errors))
        self.assertIsInstance(errors[0], Exception)

    @async_test
    async def test_as_generated_task_cancelled(self):
        async def gen(max: int = 10):
            for i in range(5):
                if i > max:
                    raise asyncio.CancelledError
                yield i
                await asyncio.sleep(0)

        gens = [gen(2), gen()]
        expected = list(range(3)) + list(range(5))
        results = []
        async for value in aio.as_generated(gens):
            results.append(value)
        self.assertListEqual(sorted(expected), sorted(results))

    @async_test
    async def test_as_generated_cancelled(self):
        async def gen():
            for i in range(5):
                yield i
                await asyncio.sleep(0.1)

        expected = [0, 0, 1, 1]
        results = []

        async def foo():
            gens = [gen(), gen()]
            async for value in aio.as_generated(gens):
                results.append(value)
            return results

        task = asyncio.ensure_future(foo())
        await asyncio.sleep(0.15)
        task.cancel()
        await task

        self.assertListEqual(sorted(expected), sorted(results))

    @async_test
    async def test_gather_input_types(self):
        async def fn(arg):
            await asyncio.sleep(0.001)
            return arg

        fns = [fn(1), asyncio.ensure_future(fn(2))]
        if hasattr(asyncio, "create_task"):
            # 3.7 only
            fns.append(asyncio.create_task(fn(3)))
        else:
            fns.append(fn(3))

        result = await aio.gather(*fns)
        self.assertEqual([1, 2, 3], result)

    @async_test
    async def test_gather_limited(self):
        max_counter = 0
        counter = 0

        async def fn(arg):
            nonlocal counter, max_counter
            counter += 1
            max_counter = max(max_counter, counter)
            await asyncio.sleep(0.001)
            counter -= 1
            return arg

        # Limit of 2
        result = await aio.gather(*[fn(i) for i in range(10)], limit=2)
        self.assertEqual(2, max_counter)
        self.assertEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], result)

        # No limit
        result = await aio.gather(*[fn(i) for i in range(10)])
        self.assertEqual(
            10, max_counter
        )  # TODO: on a loaded machine this might be less?
        self.assertEqual([0, 1, 2, 3, 4, 5, 6, 7, 8, 9], result)

    @async_test
    async def test_gather_limited_dupes(self):
        async def fn(arg):
            await asyncio.sleep(0.001)
            return arg

        f = fn(1)
        g = fn(2)
        result = await aio.gather(f, f, f, g, f, g, limit=2)
        self.assertEqual([1, 1, 1, 2, 1, 2], result)

        f = fn(1)
        g = fn(2)
        result = await aio.gather(f, f, f, g, f, g)
        self.assertEqual([1, 1, 1, 2, 1, 2], result)

    @async_test
    async def test_gather_with_exceptions(self):
        class MyException(Exception):
            pass

        async def fn(arg, fail=False):
            await asyncio.sleep(arg)
            if fail:
                raise MyException(arg)
            return arg

        with self.assertRaises(MyException):
            await aio.gather(fn(0.002, fail=True), fn(0.001))

        result = await aio.gather(
            fn(0.002, fail=True), fn(0.001), return_exceptions=True
        )
        self.assertEqual(result[1], 0.001)
        self.assertIsInstance(result[0], MyException)

    @async_test
    async def test_gather_cancel(self):
        cancelled = False
        started = False

        async def _fn():
            nonlocal started, cancelled
            try:
                started = True
                await asyncio.sleep(10)  # might as well be forever
            except asyncio.CancelledError:
                nonlocal cancelled
                cancelled = True
                raise

        async def _gather():
            await aio.gather(_fn())

        if hasattr(asyncio, "create_task"):
            # 3.7+ only
            task = asyncio.create_task(_gather())
        else:
            task = asyncio.ensure_future(_gather())
        # to insure the gather actually runs
        await asyncio.sleep(0)
        task.cancel()
        with self.assertRaises(asyncio.CancelledError):
            await task
        self.assertTrue(started)
        self.assertTrue(cancelled)