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
|
from __future__ import annotations
from unittest.mock import Mock
import pytest
from kombu.utils.scheduling import FairCycle, cycle_by_name
class MyEmpty(Exception):
pass
def consume(fun, n):
r = []
for i in range(n):
r.append(fun(Mock(name='callback')))
return r
class test_FairCycle:
def test_cycle(self):
resources = ['a', 'b', 'c', 'd', 'e']
callback = Mock(name='callback')
def echo(r, timeout=None):
return r
# cycle should be ['a', 'b', 'c', 'd', 'e', ... repeat]
cycle = FairCycle(echo, resources, MyEmpty)
for i in range(len(resources)):
assert cycle.get(callback) == resources[i]
for i in range(len(resources)):
assert cycle.get(callback) == resources[i]
def test_cycle_breaks(self):
resources = ['a', 'b', 'c', 'd', 'e']
def echo(r, callback):
if r == 'c':
raise MyEmpty(r)
return r
cycle = FairCycle(echo, resources, MyEmpty)
assert consume(cycle.get, len(resources)) == [
'a', 'b', 'd', 'e', 'a',
]
assert consume(cycle.get, len(resources)) == [
'b', 'd', 'e', 'a', 'b',
]
cycle2 = FairCycle(echo, ['c', 'c'], MyEmpty)
with pytest.raises(MyEmpty):
consume(cycle2.get, 3)
def test_cycle_no_resources(self):
cycle = FairCycle(None, [], MyEmpty)
cycle.pos = 10
with pytest.raises(MyEmpty):
cycle._next()
def test__repr__(self):
assert repr(FairCycle(lambda x: x, [1, 2, 3], MyEmpty))
def test_round_robin_cycle():
it = cycle_by_name('round_robin')(['A', 'B', 'C'])
assert it.consume(3) == ['A', 'B', 'C']
it.rotate('B')
assert it.consume(3) == ['A', 'C', 'B']
it.rotate('A')
assert it.consume(3) == ['C', 'B', 'A']
it.rotate('A')
assert it.consume(3) == ['C', 'B', 'A']
it.rotate('C')
assert it.consume(3) == ['B', 'A', 'C']
def test_priority_cycle():
it = cycle_by_name('priority')(['A', 'B', 'C'])
assert it.consume(3) == ['A', 'B', 'C']
it.rotate('B')
assert it.consume(3) == ['A', 'B', 'C']
it.rotate('A')
assert it.consume(3) == ['A', 'B', 'C']
it.rotate('A')
assert it.consume(3) == ['A', 'B', 'C']
it.rotate('C')
assert it.consume(3) == ['A', 'B', 'C']
def test_sorted_cycle():
it = cycle_by_name('sorted')(['B', 'C', 'A'])
assert it.consume(3) == ['A', 'B', 'C']
it.rotate('B')
assert it.consume(3) == ['A', 'B', 'C']
it.rotate('A')
assert it.consume(3) == ['A', 'B', 'C']
it.rotate('A')
assert it.consume(3) == ['A', 'B', 'C']
it.rotate('C')
assert it.consume(3) == ['A', 'B', 'C']
|