Debian Codegraph @

t/unit/utils/test_functional.py

raw
1 import collections
2 import sys
3
4 import pytest
5 from kombu.utils.functional import lazy
6
7 from celery.utils.functional import (DummyContext, first, firstmethod, fun_accepts_kwargs, fun_takes_argument,
8 head_from_fun, is_numeric_value, lookahead, maybe_list, mlazy, padlist, regen,
9 seq_concat_item, seq_concat_seq)
10
11
12 def test_DummyContext():
13 with DummyContext():
14 pass
15 with pytest.raises(KeyError):
16 with DummyContext():
17 raise KeyError()
18
19
20 @pytest.mark.parametrize('items,n,default,expected', [
21 (['George', 'Costanza', 'NYC'], 3, None,
22 ['George', 'Costanza', 'NYC']),
23 (['George', 'Costanza'], 3, None,
24 ['George', 'Costanza', None]),
25 (['George', 'Costanza', 'NYC'], 4, 'Earth',
26 ['George', 'Costanza', 'NYC', 'Earth']),
27 ])
28 def test_padlist(items, n, default, expected):
29 assert padlist(items, n, default=default) == expected
30
31
32 class test_firstmethod:
33
34 def test_AttributeError(self):
35 assert firstmethod('foo')([object()]) is None
36
37 def test_handles_lazy(self):
38
39 class A:
40
41 def __init__(self, value=None):
42 self.value = value
43
44 def m(self):
45 return self.value
46
47 assert 'four' == firstmethod('m')([
48 A(), A(), A(), A('four'), A('five')])
49 assert 'four' == firstmethod('m')([
50 A(), A(), A(), lazy(lambda: A('four')), A('five')])
51
52
53 def test_first():
54 iterations = [0]
55
56 def predicate(value):
57 iterations[0] += 1
58 if value == 5:
59 return True
60 return False
61
62 assert first(predicate, range(10)) == 5
63 assert iterations[0] == 6
64
65 iterations[0] = 0
66 assert first(predicate, range(10, 20)) is None
67 assert iterations[0] == 10
68
69
70 def test_lookahead():
71 assert list(lookahead(x for x in range(6))) == [(0, 1), (1, 2), (2, 3), (3, 4), (4, 5), (5, None)]
72
73
74 def test_maybe_list():
75 assert maybe_list(1) == [1]
76 assert maybe_list([1]) == [1]
77 assert maybe_list(None) is None
78
79
80 def test_mlazy():
81 it = iter(range(20, 30))
82 p = mlazy(it.__next__)
83 assert p() == 20
84 assert p.evaluated
85 assert p() == 20
86 assert repr(p) == '20'
87
88
89 class test_regen:
90
91 def test_list(self):
92 l = [1, 2]
93 r = regen(iter(l))
94 assert regen(l) is l
95 assert r == l
96 assert r == l # again
97 assert r.__length_hint__() == 0
98
99 fun, args = r.__reduce__()
100 assert fun(*args) == l
101
102 @pytest.fixture
103 def g(self):
104 return regen(iter(list(range(10))))
105
106 def test_gen(self, g):
107 assert g[7] == 7
108 assert g[6] == 6
109 assert g[5] == 5
110 assert g[4] == 4
111 assert g[3] == 3
112 assert g[2] == 2
113 assert g[1] == 1
114 assert g[0] == 0
115 assert g.data, list(range(10))
116 assert g[8] == 8
117 assert g[0] == 0
118
119 def test_gen__index_2(self, g):
120 assert g[0] == 0
121 assert g[1] == 1
122 assert g.data == list(range(10))
123
124 def test_gen__index_error(self, g):
125 assert g[0] == 0
126 with pytest.raises(IndexError):
127 g[11]
128 assert list(iter(g)) == list(range(10))
129
130 def test_gen__negative_index(self, g):
131 assert g[-1] == 9
132 assert g[-2] == 8
133 assert g[-3] == 7
134 assert g[-4] == 6
135 assert g[-5] == 5
136 assert g[5] == 5
137 assert g.data == list(range(10))
138
139 assert list(iter(g)) == list(range(10))
140
141 def test_nonzero__does_not_consume_more_than_first_item(self):
142 def build_generator():
143 yield 1
144 pytest.fail("generator should not consume past first item")
145 yield 2
146
147 g = regen(build_generator())
148 assert bool(g)
149 assert g[0] == 1
150
151 def test_nonzero__empty_iter(self):
152 assert not regen(iter([]))
153
154 def test_deque(self):
155 original_list = [42]
156 d = collections.deque(original_list)
157 # Confirm that concretising a `regen()` instance repeatedly for an
158 # equality check always returns the original list
159 g = regen(d)
160 assert g == original_list
161 assert g == original_list
162
163 def test_repr(self):
164 def die():
165 raise AssertionError("Generator died")
166 yield None
167
168 # Confirm that `regen()` instances are not concretised when represented
169 g = regen(die())
170 assert "..." in repr(g)
171
172 def test_partial_reconcretisation(self):
173 class WeirdIterator():
174 def __init__(self, iter_):
175 self.iter_ = iter_
176 self._errored = False
177
178 def __iter__(self):
179 yield from self.iter_
180 if not self._errored:
181 try:
182 # This should stop the regen instance from marking
183 # itself as being done
184 raise AssertionError("Iterator errored")
185 finally:
186 self._errored = True
187
188 original_list = list(range(42))
189 g = regen(WeirdIterator(original_list))
190 iter_g = iter(g)
191 for e in original_list:
192 assert e == next(iter_g)
193 with pytest.raises(AssertionError, match="Iterator errored"):
194 next(iter_g)
195 # The following checks are for the known "misbehaviour"
196 assert getattr(g, "_regen__done") is False
197 # If the `regen()` instance doesn't think it's done then it'll dupe the
198 # elements from the underlying iterator if it can be reused
199 iter_g = iter(g)
200 for e in original_list * 2:
201 assert next(iter_g) == e
202 with pytest.raises(StopIteration):
203 next(iter_g)
204 assert getattr(g, "_regen__done") is True
205 # Finally we xfail this test to keep track of it
206 raise pytest.xfail(reason="#6794")
207
208 def test_length_hint_passthrough(self, g):
209 assert g.__length_hint__() == 10
210
211 def test_getitem_repeated(self, g):
212 halfway_idx = g.__length_hint__() // 2
213 assert g[halfway_idx] == halfway_idx
214 # These are now concretised so they should be returned without any work
215 assert g[halfway_idx] == halfway_idx
216 for i in range(halfway_idx + 1):
217 assert g[i] == i
218 # This should only need to concretise one more element
219 assert g[halfway_idx + 1] == halfway_idx + 1
220
221 def test_done_does_not_lag(self, g):
222 """
223 Don't allow regen to return from `__iter__()` and check `__done`.
224 """
225 # The range we zip with here should ensure that the `regen.__iter__`
226 # call never gets to return since we never attempt a failing `next()`
227 len_g = g.__length_hint__()
228 for i, __ in zip(range(len_g), g):
229 assert getattr(g, "_regen__done") is (i == len_g - 1)
230 # Just for sanity, check against a specific `bool` here
231 assert getattr(g, "_regen__done") is True
232
233 def test_lookahead_consume(self, subtests):
234 """
235 Confirm that regen looks ahead by a single item as expected.
236 """
237 def g():
238 yield from ["foo", "bar"]
239 raise pytest.fail("This should never be reached")
240
241 with subtests.test(msg="bool does not overconsume"):
242 assert bool(regen(g()))
243 with subtests.test(msg="getitem 0th does not overconsume"):
244 assert regen(g())[0] == "foo"
245 with subtests.test(msg="single iter does not overconsume"):
246 assert next(iter(regen(g()))) == "foo"
247
248 class ExpectedException(BaseException):
249 pass
250
251 def g2():
252 yield from ["foo", "bar"]
253 raise ExpectedException()
254
255 with subtests.test(msg="getitem 1th does overconsume"):
256 r = regen(g2())
257 with pytest.raises(ExpectedException):
258 r[1]
259 # Confirm that the item was concretised anyway
260 assert r[1] == "bar"
261 with subtests.test(msg="full iter does overconsume"):
262 r = regen(g2())
263 with pytest.raises(ExpectedException):
264 for _ in r:
265 pass
266 # Confirm that the items were concretised anyway
267 assert r == ["foo", "bar"]
268 with subtests.test(msg="data access does overconsume"):
269 r = regen(g2())
270 with pytest.raises(ExpectedException):
271 r.data
272 # Confirm that the items were concretised anyway
273 assert r == ["foo", "bar"]
274
275
276 class test_head_from_fun:
277
278 def test_from_cls(self):
279 class X:
280 def __call__(x, y, kwarg=1):
281 pass
282
283 g = head_from_fun(X())
284 with pytest.raises(TypeError):
285 g(1)
286 g(1, 2)
287 g(1, 2, kwarg=3)
288
289 def test_from_fun(self):
290 def f(x, y, kwarg=1):
291 pass
292 g = head_from_fun(f)
293 with pytest.raises(TypeError):
294 g(1)
295 g(1, 2)
296 g(1, 2, kwarg=3)
297
298 def test_regression_3678(self):
299 local = {}
300 fun = ('def f(foo, *args, bar="", **kwargs):'
301 ' return foo, args, bar')
302 exec(fun, {}, local)
303
304 g = head_from_fun(local['f'])
305 g(1)
306 g(1, 2, 3, 4, bar=100)
307 with pytest.raises(TypeError):
308 g(bar=100)
309
310 def test_from_fun_with_hints(self):
311 local = {}
312 fun = ('def f_hints(x: int, y: int, kwarg: int=1):'
313 ' pass')
314 exec(fun, {}, local)
315 f_hints = local['f_hints']
316
317 g = head_from_fun(f_hints)
318 with pytest.raises(TypeError):
319 g(1)
320 g(1, 2)
321 g(1, 2, kwarg=3)
322
323 def test_from_fun_forced_kwargs(self):
324 local = {}
325 fun = ('def f_kwargs(*, a, b="b", c=None):'
326 ' return')
327 exec(fun, {}, local)
328 f_kwargs = local['f_kwargs']
329
330 g = head_from_fun(f_kwargs)
331 with pytest.raises(TypeError):
332 g(1)
333
334 g(a=1)
335 g(a=1, b=2)
336 g(a=1, b=2, c=3)
337
338 def test_classmethod(self):
339 class A:
340 @classmethod
341 def f(cls, x):
342 return x
343
344 fun = head_from_fun(A.f, bound=False)
345 assert fun(A, 1) == 1
346
347 fun = head_from_fun(A.f, bound=True)
348 assert fun(1) == 1
349
350 def test_kwonly_required_args(self):
351 local = {}
352 fun = ('def f_kwargs_required(*, a="a", b, c=None):'
353 ' return')
354 exec(fun, {}, local)
355 f_kwargs_required = local['f_kwargs_required']
356 g = head_from_fun(f_kwargs_required)
357
358 with pytest.raises(TypeError):
359 g(1)
360
361 with pytest.raises(TypeError):
362 g(a=1)
363
364 with pytest.raises(TypeError):
365 g(c=1)
366
367 with pytest.raises(TypeError):
368 g(a=2, c=1)
369
370 g(b=3)
371
372 @pytest.mark.skipif(sys.version_info < (3, 14), reason="PEP 649 deferred annotations require Python 3.14+")
373 def test_type_checking_annotation(self):
374 # Regression test for https://github.com/celery/celery/discussions/10099
375 # On Python 3.14+, annotations are deferred (PEP 649). Functions with
376 # annotations referencing TYPE_CHECKING-only types must not raise NameError.
377 local = {}
378 exec('def f(args: Sequence[str], x: int = 0): return args', {}, local)
379 f = local['f']
380
381 g = head_from_fun(f)
382 with pytest.raises(TypeError):
383 g()
384 g(1)
385 g(1, 2)
386
387
388 class test_fun_takes_argument:
389
390 def test_starkwargs(self):
391 assert fun_takes_argument('foo', lambda **kw: 1)
392
393 def test_named(self):
394 assert fun_takes_argument('foo', lambda a, foo, bar: 1)
395
396 def fun(a, b, c, d):
397 return 1
398
399 assert fun_takes_argument('foo', fun, position=4)
400
401 def test_starargs(self):
402 assert fun_takes_argument('foo', lambda a, *args: 1)
403
404 def test_does_not(self):
405 assert not fun_takes_argument('foo', lambda a, bar, baz: 1)
406 assert not fun_takes_argument('foo', lambda: 1)
407
408 def fun(a, b, foo):
409 return 1
410
411 assert not fun_takes_argument('foo', fun, position=4)
412
413
414 @pytest.mark.parametrize('a,b,expected', [
415 ((1, 2, 3), [4, 5], (1, 2, 3, 4, 5)),
416 ((1, 2), [3, 4, 5], [1, 2, 3, 4, 5]),
417 ([1, 2, 3], (4, 5), [1, 2, 3, 4, 5]),
418 ([1, 2], (3, 4, 5), (1, 2, 3, 4, 5)),
419 ])
420 def test_seq_concat_seq(a, b, expected):
421 res = seq_concat_seq(a, b)
422 assert type(res) is type(expected)
423 assert res == expected
424
425
426 @pytest.mark.parametrize('a,b,expected', [
427 ((1, 2, 3), 4, (1, 2, 3, 4)),
428 ([1, 2, 3], 4, [1, 2, 3, 4]),
429 ])
430 def test_seq_concat_item(a, b, expected):
431 res = seq_concat_item(a, b)
432 assert type(res) is type(expected)
433 assert res == expected
434
435
436 class StarKwargsCallable:
437
438 def __call__(self, **kwargs):
439 return 1
440
441
442 class StarArgsStarKwargsCallable:
443
444 def __call__(self, *args, **kwargs):
445 return 1
446
447
448 class StarArgsCallable:
449
450 def __call__(self, *args):
451 return 1
452
453
454 class ArgsCallable:
455
456 def __call__(self, a, b):
457 return 1
458
459
460 class ArgsStarKwargsCallable:
461
462 def __call__(self, a, b, **kwargs):
463 return 1
464
465
466 class test_fun_accepts_kwargs:
467
468 @pytest.mark.parametrize('fun', [
469 lambda a, b, **kwargs: 1,
470 lambda *args, **kwargs: 1,
471 lambda foo=1, **kwargs: 1,
472 StarKwargsCallable(),
473 StarArgsStarKwargsCallable(),
474 ArgsStarKwargsCallable(),
475 ])
476 def test_accepts(self, fun):
477 assert fun_accepts_kwargs(fun)
478
479 @pytest.mark.parametrize('fun', [
480 lambda a: 1,
481 lambda a, b: 1,
482 lambda *args: 1,
483 lambda a, kw1=1, kw2=2: 1,
484 StarArgsCallable(),
485 ArgsCallable(),
486 ])
487 def test_rejects(self, fun):
488 assert not fun_accepts_kwargs(fun)
489
490 @pytest.mark.skipif(sys.version_info < (3, 14), reason="PEP 649 deferred annotations require Python 3.14+")
491 def test_type_checking_annotation(self):
492 # Regression test for https://github.com/celery/celery/discussions/10099
493 # On Python 3.14+, annotations are deferred (PEP 649). Calling
494 # fun_accepts_kwargs on a function whose annotations reference
495 # TYPE_CHECKING-only types must not raise NameError.
496 #
497 # This reproduces the failure seen with on_after_finalize.connect:
498 # def setup_periodic_tasks(sender: Celery, **kwargs: object) -> None: ...
499 # where 'Celery' is only imported under TYPE_CHECKING.
500 local = {}
501 exec('def f(sender: Celery, **kwargs: object) -> None: pass', {}, local)
502 f = local['f']
503 assert fun_accepts_kwargs(f) is True
504
505 exec('def g(sender: Celery) -> None: pass', {}, local)
506 g = local['g']
507 assert fun_accepts_kwargs(g) is False
508
509
510 @pytest.mark.parametrize('value,expected', [
511 (5, True),
512 (5.0, True),
513 (0, True),
514 (0.0, True),
515 (True, False),
516 ('value', False),
517 ('5', False),
518 ('5.0', False),
519 (None, False),
520 ])
521 def test_is_numeric_value(value, expected):
522 res = is_numeric_value(value)
523 assert type(res) is type(expected)
524 assert res == expected