Debian Codegraph @

t/unit/worker/test_state.py

raw
1 import os
2 import pickle
3 import sys
4 from importlib import import_module
5 from time import time
6 from unittest.mock import Mock, patch
7
8 import pytest
9
10 from celery import uuid
11 from celery.exceptions import WorkerShutdown, WorkerTerminate
12 from celery.platforms import EX_OK
13 from celery.utils.collections import LimitedSet
14 from celery.worker import state
15
16
17 @pytest.fixture
18 def reset_state():
19 yield
20 state.active_requests.clear()
21 state.revoked.clear()
22 state.revoked_stamps.clear()
23 state.total_count.clear()
24
25
26 class MockShelve(dict):
27 filename = None
28 in_sync = False
29 closed = False
30
31 def open(self, filename, **kwargs):
32 self.filename = filename
33 return self
34
35 def sync(self):
36 self.in_sync = True
37
38 def close(self):
39 self.closed = True
40
41
42 class MyPersistent(state.Persistent):
43 storage = MockShelve()
44
45
46 class test_maybe_shutdown:
47
48 def teardown_method(self):
49 state.should_stop = None
50 state.should_terminate = None
51
52 def test_should_stop(self):
53 state.should_stop = True
54 with pytest.raises(WorkerShutdown):
55 state.maybe_shutdown()
56 state.should_stop = 0
57 with pytest.raises(WorkerShutdown):
58 state.maybe_shutdown()
59 state.should_stop = False
60 try:
61 state.maybe_shutdown()
62 except SystemExit:
63 raise RuntimeError('should not have exited')
64 state.should_stop = None
65 try:
66 state.maybe_shutdown()
67 except SystemExit:
68 raise RuntimeError('should not have exited')
69
70 state.should_stop = 0
71 try:
72 state.maybe_shutdown()
73 except SystemExit as exc:
74 assert exc.code == 0
75 else:
76 raise RuntimeError('should have exited')
77
78 state.should_stop = 303
79 try:
80 state.maybe_shutdown()
81 except SystemExit as exc:
82 assert exc.code == 303
83 else:
84 raise RuntimeError('should have exited')
85
86 @pytest.mark.parametrize('should_stop', (None, False, True, EX_OK))
87 def test_should_terminate(self, should_stop):
88 state.should_stop = should_stop
89 state.should_terminate = True
90 with pytest.raises(WorkerTerminate):
91 state.maybe_shutdown()
92
93
94 @pytest.mark.usefixtures('reset_state')
95 class test_Persistent:
96
97 @pytest.fixture
98 def p(self):
99 return MyPersistent(state, filename='celery-state')
100
101 def test_close_twice(self, p):
102 p._is_open = False
103 p.close()
104
105 def test_constructor(self, p):
106 assert p.db == {}
107 assert p.db.filename == p.filename
108
109 def test_save(self, p):
110 p.db['foo'] = 'bar'
111 p.save()
112 assert p.db.in_sync
113 assert p.db.closed
114
115 def add_revoked(self, p, *ids):
116 for id in ids:
117 p.db.setdefault('revoked', LimitedSet()).add(id)
118
119 def test_merge(self, p, data=['foo', 'bar', 'baz']):
120 state.revoked.update(data)
121 p.merge()
122 for item in data:
123 assert item in state.revoked
124
125 def test_merge_dict(self, p):
126 p.clock = Mock()
127 p.clock.adjust.return_value = 626
128 d = {'revoked': {'abc': time()}, 'clock': 313}
129 p._merge_with(d)
130 p.clock.adjust.assert_called_with(313)
131 assert d['clock'] == 626
132 assert 'abc' in state.revoked
133
134 def test_sync_clock_and_purge(self, p):
135 passthrough = Mock()
136 passthrough.side_effect = lambda x: x
137 with patch('celery.worker.state.revoked') as revoked:
138 d = {'clock': 0}
139 p.clock = Mock()
140 p.clock.forward.return_value = 627
141 p._dumps = passthrough
142 p.compress = passthrough
143 p._sync_with(d)
144 revoked.purge.assert_called_with()
145 assert d['clock'] == 627
146 assert 'revoked' not in d
147 assert d['zrevoked'] is revoked
148
149 def test_sync(self, p,
150 data1=['foo', 'bar', 'baz'], data2=['baz', 'ini', 'koz']):
151 self.add_revoked(p, *data1)
152 for item in data2:
153 state.revoked.add(item)
154 p.sync()
155
156 assert p.db['zrevoked']
157 pickled = p.decompress(p.db['zrevoked'])
158 assert pickled
159 saved = pickle.loads(pickled)
160 for item in data2:
161 assert item in saved
162
163
164 class SimpleReq:
165
166 def __init__(self, name):
167 self.id = uuid()
168 self.name = name
169
170
171 @pytest.mark.usefixtures('reset_state')
172 class test_state:
173
174 def test_accepted(self, requests=[SimpleReq('foo'),
175 SimpleReq('bar'),
176 SimpleReq('baz'),
177 SimpleReq('baz')]):
178 for request in requests:
179 state.task_accepted(request)
180 for req in requests:
181 assert req in state.active_requests
182 assert state.total_count['foo'] == 1
183 assert state.total_count['bar'] == 1
184 assert state.total_count['baz'] == 2
185
186 def test_ready(self, requests=[SimpleReq('foo'),
187 SimpleReq('bar')]):
188 for request in requests:
189 state.task_accepted(request)
190 assert len(state.active_requests) == 2
191 for request in requests:
192 state.task_ready(request)
193 assert len(state.active_requests) == 0
194
195
196 class test_state_configuration():
197
198 @staticmethod
199 def import_state():
200 with patch.dict(sys.modules):
201 del sys.modules['celery.worker.state']
202 return import_module('celery.worker.state')
203
204 @patch.dict(os.environ, {
205 'CELERY_WORKER_REVOKES_MAX': '50001',
206 'CELERY_WORKER_SUCCESSFUL_MAX': '1001',
207 'CELERY_WORKER_REVOKE_EXPIRES': '10801',
208 'CELERY_WORKER_SUCCESSFUL_EXPIRES': '10801',
209 })
210 def test_custom_configuration(self):
211 state = self.import_state()
212 assert state.REVOKES_MAX == 50001
213 assert state.SUCCESSFUL_MAX == 1001
214 assert state.REVOKE_EXPIRES == 10801
215 assert state.SUCCESSFUL_EXPIRES == 10801
216
217 def test_default_configuration(self):
218 state = self.import_state()
219 assert state.REVOKES_MAX == 50000
220 assert state.SUCCESSFUL_MAX == 1000
221 assert state.REVOKE_EXPIRES == 10800
222 assert state.SUCCESSFUL_EXPIRES == 10800