| 1 |
import os |
| 2 |
import socket |
| 3 |
import sys |
| 4 |
from collections import deque |
| 5 |
from datetime import datetime, timedelta |
| 6 |
from functools import partial |
| 7 |
from queue import Empty |
| 8 |
from queue import Queue as FastQueue |
| 9 |
from threading import Event |
| 10 |
from unittest.mock import Mock, patch |
| 11 |
|
| 12 |
import pytest |
| 13 |
from amqp import ChannelError |
| 14 |
from kombu import Connection |
| 15 |
from kombu.asynchronous import get_event_loop |
| 16 |
from kombu.common import QoS, ignore_errors |
| 17 |
from kombu.transport.base import Message |
| 18 |
from kombu.transport.memory import Transport |
| 19 |
from kombu.utils.uuid import uuid |
| 20 |
|
| 21 |
import t.skip |
| 22 |
from celery.apps.worker import safe_say |
| 23 |
from celery.bootsteps import CLOSE, RUN, TERMINATE, StartStopStep |
| 24 |
from celery.concurrency.base import BasePool |
| 25 |
from celery.exceptions import (ImproperlyConfigured, InvalidTaskError, TaskRevokedError, WorkerShutdown, |
| 26 |
WorkerTerminate) |
| 27 |
from celery.platforms import EX_FAILURE |
| 28 |
from celery.utils.nodenames import worker_direct |
| 29 |
from celery.utils.serialization import pickle |
| 30 |
from celery.utils.timer2 import Timer |
| 31 |
from celery.worker import autoscale, components, consumer, state |
| 32 |
from celery.worker import worker as worker_module |
| 33 |
from celery.worker.consumer import Consumer |
| 34 |
from celery.worker.pidbox import gPidbox |
| 35 |
from celery.worker.request import Request |
| 36 |
|
| 37 |
|
| 38 |
def MockStep(step=None): |
| 39 |
if step is None: |
| 40 |
step = Mock(name='step') |
| 41 |
else: |
| 42 |
step.blueprint = Mock(name='step.blueprint') |
| 43 |
step.blueprint.name = 'MockNS' |
| 44 |
step.name = f'MockStep({id(step)})' |
| 45 |
return step |
| 46 |
|
| 47 |
|
| 48 |
def mock_event_dispatcher(): |
| 49 |
evd = Mock(name='event_dispatcher') |
| 50 |
evd.groups = ['worker'] |
| 51 |
evd._outbound_buffer = deque() |
| 52 |
return evd |
| 53 |
|
| 54 |
|
| 55 |
def find_step(obj, typ): |
| 56 |
return obj.blueprint.steps[typ.name] |
| 57 |
|
| 58 |
|
| 59 |
def create_message(channel, **data): |
| 60 |
data.setdefault('id', uuid()) |
| 61 |
m = Message(body=pickle.dumps(dict(**data)), |
| 62 |
channel=channel, |
| 63 |
content_type='application/x-python-serialize', |
| 64 |
content_encoding='binary', |
| 65 |
delivery_info={'consumer_tag': 'mock'}) |
| 66 |
m.accept = ['application/x-python-serialize'] |
| 67 |
return m |
| 68 |
|
| 69 |
|
| 70 |
class ConsumerCase: |
| 71 |
|
| 72 |
def create_task_message(self, channel, *args, **kwargs): |
| 73 |
m = self.TaskMessage(*args, **kwargs) |
| 74 |
m.channel = channel |
| 75 |
m.delivery_info = {'consumer_tag': 'mock'} |
| 76 |
return m |
| 77 |
|
| 78 |
|
| 79 |
class test_Consumer(ConsumerCase): |
| 80 |
|
| 81 |
def setup_method(self): |
| 82 |
self.buffer = FastQueue() |
| 83 |
self.timer = Timer() |
| 84 |
|
| 85 |
@self.app.task(shared=False) |
| 86 |
def foo_task(x, y, z): |
| 87 |
return x * y * z |
| 88 |
self.foo_task = foo_task |
| 89 |
|
| 90 |
def teardown_method(self): |
| 91 |
self.timer.stop() |
| 92 |
|
| 93 |
def LoopConsumer(self, buffer=None, controller=None, timer=None, app=None, |
| 94 |
without_mingle=True, without_gossip=True, |
| 95 |
without_heartbeat=True, **kwargs): |
| 96 |
if controller is None: |
| 97 |
controller = Mock(name='.controller') |
| 98 |
buffer = buffer if buffer is not None else self.buffer.put |
| 99 |
timer = timer if timer is not None else self.timer |
| 100 |
app = app if app is not None else self.app |
| 101 |
c = Consumer( |
| 102 |
buffer, |
| 103 |
timer=timer, |
| 104 |
app=app, |
| 105 |
controller=controller, |
| 106 |
without_mingle=without_mingle, |
| 107 |
without_gossip=without_gossip, |
| 108 |
without_heartbeat=without_heartbeat, |
| 109 |
**kwargs |
| 110 |
) |
| 111 |
c.task_consumer = Mock(name='.task_consumer') |
| 112 |
c.qos = QoS(c.task_consumer.qos, 10) |
| 113 |
c.connection = Mock(name='.connection') |
| 114 |
c.connection.connection_errors = () |
| 115 |
c.connection.channel_errors = () |
| 116 |
c.controller = c.app.WorkController() |
| 117 |
c.heart = Mock(name='.heart') |
| 118 |
c.controller.consumer = c |
| 119 |
c.pool = c.controller.pool = Mock(name='.controller.pool') |
| 120 |
c.node = Mock(name='.node') |
| 121 |
c.event_dispatcher = mock_event_dispatcher() |
| 122 |
return c |
| 123 |
|
| 124 |
def NoopConsumer(self, *args, **kwargs): |
| 125 |
c = self.LoopConsumer(*args, **kwargs) |
| 126 |
c.loop = Mock(name='.loop') |
| 127 |
return c |
| 128 |
|
| 129 |
def test_info(self): |
| 130 |
c = self.NoopConsumer() |
| 131 |
c.connection.info.return_value = {'foo': 'bar'} |
| 132 |
c.controller.pool.info.return_value = [Mock(), Mock()] |
| 133 |
info = c.controller.stats() |
| 134 |
assert info['prefetch_count'] == 10 |
| 135 |
assert info['broker'] |
| 136 |
|
| 137 |
def test_start_when_closed(self): |
| 138 |
c = self.NoopConsumer() |
| 139 |
c.blueprint.state = CLOSE |
| 140 |
c.start() |
| 141 |
|
| 142 |
def test_connection(self): |
| 143 |
c = self.NoopConsumer() |
| 144 |
|
| 145 |
c.blueprint.start(c) |
| 146 |
assert isinstance(c.connection, Connection) |
| 147 |
|
| 148 |
c.blueprint.state = RUN |
| 149 |
c.event_dispatcher = None |
| 150 |
c.blueprint.restart(c) |
| 151 |
assert c.connection |
| 152 |
|
| 153 |
c.blueprint.state = RUN |
| 154 |
c.shutdown() |
| 155 |
assert c.connection is None |
| 156 |
assert c.task_consumer is None |
| 157 |
|
| 158 |
c.blueprint.start(c) |
| 159 |
assert isinstance(c.connection, Connection) |
| 160 |
c.blueprint.restart(c) |
| 161 |
|
| 162 |
c.stop() |
| 163 |
c.shutdown() |
| 164 |
assert c.connection is None |
| 165 |
assert c.task_consumer is None |
| 166 |
|
| 167 |
def test_close_connection(self): |
| 168 |
c = self.NoopConsumer() |
| 169 |
c.blueprint.state = RUN |
| 170 |
step = find_step(c, consumer.Connection) |
| 171 |
connection = c.connection |
| 172 |
step.shutdown(c) |
| 173 |
connection.close.assert_called() |
| 174 |
assert c.connection is None |
| 175 |
|
| 176 |
def test_close_connection__heart_shutdown(self): |
| 177 |
c = self.NoopConsumer() |
| 178 |
event_dispatcher = c.event_dispatcher |
| 179 |
heart = c.heart |
| 180 |
c.event_dispatcher.enabled = True |
| 181 |
c.blueprint.state = RUN |
| 182 |
Events = find_step(c, consumer.Events) |
| 183 |
Events.shutdown(c) |
| 184 |
Heart = find_step(c, consumer.Heart) |
| 185 |
Heart.shutdown(c) |
| 186 |
event_dispatcher.close.assert_called() |
| 187 |
heart.stop.assert_called_with() |
| 188 |
|
| 189 |
@patch('celery.worker.consumer.consumer.warn') |
| 190 |
def test_receive_message_unknown(self, warn): |
| 191 |
c = self.LoopConsumer() |
| 192 |
c.blueprint.state = RUN |
| 193 |
c.steps.pop() |
| 194 |
channel = Mock(name='.channeol') |
| 195 |
m = create_message(channel, unknown={'baz': '!!!'}) |
| 196 |
|
| 197 |
callback = self._get_on_message(c) |
| 198 |
callback(m) |
| 199 |
warn.assert_called() |
| 200 |
|
| 201 |
@patch('celery.worker.strategy.to_timestamp') |
| 202 |
def test_receive_message_eta_OverflowError(self, to_timestamp): |
| 203 |
to_timestamp.side_effect = OverflowError() |
| 204 |
c = self.LoopConsumer() |
| 205 |
c.blueprint.state = RUN |
| 206 |
c.steps.pop() |
| 207 |
m = self.create_task_message( |
| 208 |
Mock(), self.foo_task.name, |
| 209 |
args=('2, 2'), kwargs={}, |
| 210 |
eta=datetime.now().isoformat(), |
| 211 |
) |
| 212 |
c.update_strategies() |
| 213 |
callback = self._get_on_message(c) |
| 214 |
callback(m) |
| 215 |
assert m.acknowledged |
| 216 |
|
| 217 |
@patch('celery.worker.consumer.consumer.error') |
| 218 |
def test_receive_message_InvalidTaskError(self, error): |
| 219 |
c = self.LoopConsumer() |
| 220 |
c.blueprint.state = RUN |
| 221 |
c.steps.pop() |
| 222 |
m = self.create_task_message( |
| 223 |
Mock(), self.foo_task.name, |
| 224 |
args=(1, 2), kwargs='foobarbaz', id=1) |
| 225 |
c.update_strategies() |
| 226 |
strategy = c.strategies[self.foo_task.name] = Mock(name='strategy') |
| 227 |
strategy.side_effect = InvalidTaskError() |
| 228 |
|
| 229 |
callback = self._get_on_message(c) |
| 230 |
callback(m) |
| 231 |
error.assert_called() |
| 232 |
assert 'Received invalid task message' in error.call_args[0][0] |
| 233 |
|
| 234 |
@patch('celery.worker.consumer.consumer.crit') |
| 235 |
def test_on_decode_error(self, crit): |
| 236 |
c = self.LoopConsumer() |
| 237 |
|
| 238 |
class MockMessage(Mock): |
| 239 |
content_type = 'application/x-msgpack' |
| 240 |
content_encoding = 'binary' |
| 241 |
body = 'foobarbaz' |
| 242 |
|
| 243 |
message = MockMessage() |
| 244 |
c.on_decode_error(message, KeyError('foo')) |
| 245 |
assert message.ack.call_count |
| 246 |
assert "Can't decode message body" in crit.call_args[0][0] |
| 247 |
|
| 248 |
def _get_on_message(self, c): |
| 249 |
if c.qos is None: |
| 250 |
c.qos = Mock() |
| 251 |
c.task_consumer = Mock() |
| 252 |
c.event_dispatcher = mock_event_dispatcher() |
| 253 |
c.connection = Mock(name='.connection') |
| 254 |
c.connection.connection_errors = () |
| 255 |
c.connection.channel_errors = () |
| 256 |
c.connection.get_heartbeat_interval.return_value = 0 |
| 257 |
c.connection.drain_events.side_effect = WorkerShutdown() |
| 258 |
|
| 259 |
with pytest.raises(WorkerShutdown): |
| 260 |
c.loop(*c.loop_args()) |
| 261 |
assert c.task_consumer.on_message |
| 262 |
return c.task_consumer.on_message |
| 263 |
|
| 264 |
def test_receieve_message(self): |
| 265 |
c = self.LoopConsumer() |
| 266 |
c.blueprint.state = RUN |
| 267 |
m = self.create_task_message( |
| 268 |
Mock(), self.foo_task.name, |
| 269 |
args=[2, 4, 8], kwargs={}, |
| 270 |
) |
| 271 |
c.update_strategies() |
| 272 |
callback = self._get_on_message(c) |
| 273 |
callback(m) |
| 274 |
|
| 275 |
in_bucket = self.buffer.get_nowait() |
| 276 |
assert isinstance(in_bucket, Request) |
| 277 |
assert in_bucket.name == self.foo_task.name |
| 278 |
assert in_bucket.execute() == 2 * 4 * 8 |
| 279 |
assert self.timer.empty() |
| 280 |
|
| 281 |
def test_start_channel_error(self): |
| 282 |
def loop_side_effect(): |
| 283 |
yield KeyError('foo') |
| 284 |
yield SyntaxError('bar') |
| 285 |
|
| 286 |
c = self.NoopConsumer(task_events=False, pool=BasePool()) |
| 287 |
c.loop.side_effect = loop_side_effect() |
| 288 |
c.channel_errors = (KeyError,) |
| 289 |
try: |
| 290 |
with pytest.raises(KeyError): |
| 291 |
c.start() |
| 292 |
finally: |
| 293 |
c.timer and c.timer.stop() |
| 294 |
|
| 295 |
def test_start_connection_error(self): |
| 296 |
def loop_side_effect(): |
| 297 |
yield KeyError('foo') |
| 298 |
yield SyntaxError('bar') |
| 299 |
c = self.NoopConsumer(task_events=False, pool=BasePool()) |
| 300 |
c.loop.side_effect = loop_side_effect() |
| 301 |
c.pool.num_processes = 2 |
| 302 |
c.connection_errors = (KeyError,) |
| 303 |
try: |
| 304 |
with pytest.raises(SyntaxError): |
| 305 |
c.start() |
| 306 |
finally: |
| 307 |
c.timer and c.timer.stop() |
| 308 |
|
| 309 |
def test_loop_ignores_socket_timeout(self): |
| 310 |
|
| 311 |
class Connection(self.app.connection_for_read().__class__): |
| 312 |
obj = None |
| 313 |
|
| 314 |
def drain_events(self, **kwargs): |
| 315 |
self.obj.connection = None |
| 316 |
raise socket.timeout(10) |
| 317 |
|
| 318 |
c = self.NoopConsumer() |
| 319 |
c.connection = Connection(self.app.conf.broker_url) |
| 320 |
c.connection.obj = c |
| 321 |
c.qos = QoS(c.task_consumer.qos, 10) |
| 322 |
c.loop(*c.loop_args()) |
| 323 |
|
| 324 |
def test_loop_when_socket_error(self): |
| 325 |
|
| 326 |
class Connection(self.app.connection_for_read().__class__): |
| 327 |
obj = None |
| 328 |
|
| 329 |
def drain_events(self, **kwargs): |
| 330 |
self.obj.connection = None |
| 331 |
raise OSError('foo') |
| 332 |
|
| 333 |
c = self.LoopConsumer() |
| 334 |
c.blueprint.state = RUN |
| 335 |
conn = c.connection = Connection(self.app.conf.broker_url) |
| 336 |
c.connection.obj = c |
| 337 |
c.qos = QoS(c.task_consumer.qos, 10) |
| 338 |
with pytest.raises(socket.error): |
| 339 |
c.loop(*c.loop_args()) |
| 340 |
|
| 341 |
c.blueprint.state = CLOSE |
| 342 |
c.connection = conn |
| 343 |
c.loop(*c.loop_args()) |
| 344 |
|
| 345 |
def test_loop(self): |
| 346 |
|
| 347 |
class Connection(self.app.connection_for_read().__class__): |
| 348 |
obj = None |
| 349 |
|
| 350 |
def drain_events(self, **kwargs): |
| 351 |
self.obj.connection = None |
| 352 |
|
| 353 |
@property |
| 354 |
def supports_heartbeats(self): |
| 355 |
return False |
| 356 |
|
| 357 |
c = self.LoopConsumer() |
| 358 |
c.blueprint.state = RUN |
| 359 |
c.connection = Connection(self.app.conf.broker_url) |
| 360 |
c.connection.obj = c |
| 361 |
c.connection.get_heartbeat_interval = Mock(return_value=None) |
| 362 |
c.qos = QoS(c.task_consumer.qos, 10) |
| 363 |
|
| 364 |
c.loop(*c.loop_args()) |
| 365 |
c.loop(*c.loop_args()) |
| 366 |
assert c.task_consumer.consume.call_count |
| 367 |
c.task_consumer.qos.assert_called_with(prefetch_count=10) |
| 368 |
assert c.qos.value == 10 |
| 369 |
c.qos.decrement_eventually() |
| 370 |
assert c.qos.value == 9 |
| 371 |
c.qos.update() |
| 372 |
assert c.qos.value == 9 |
| 373 |
c.task_consumer.qos.assert_called_with(prefetch_count=9) |
| 374 |
|
| 375 |
def test_ignore_errors(self): |
| 376 |
c = self.NoopConsumer() |
| 377 |
c.connection_errors = (AttributeError, KeyError,) |
| 378 |
c.channel_errors = (SyntaxError,) |
| 379 |
ignore_errors(c, Mock(side_effect=AttributeError('foo'))) |
| 380 |
ignore_errors(c, Mock(side_effect=KeyError('foo'))) |
| 381 |
ignore_errors(c, Mock(side_effect=SyntaxError('foo'))) |
| 382 |
with pytest.raises(IndexError): |
| 383 |
ignore_errors(c, Mock(side_effect=IndexError('foo'))) |
| 384 |
|
| 385 |
def test_apply_eta_task(self): |
| 386 |
c = self.NoopConsumer() |
| 387 |
c.qos = QoS(None, 10) |
| 388 |
task = Mock(name='task', id='1234213') |
| 389 |
qos = c.qos.value |
| 390 |
c.apply_eta_task(task) |
| 391 |
assert task in state.reserved_requests |
| 392 |
assert c.qos.value == qos - 1 |
| 393 |
assert self.buffer.get_nowait() is task |
| 394 |
|
| 395 |
def test_receieve_message_eta_isoformat(self): |
| 396 |
c = self.LoopConsumer() |
| 397 |
c.blueprint.state = RUN |
| 398 |
c.steps.pop() |
| 399 |
m = self.create_task_message( |
| 400 |
Mock(), self.foo_task.name, |
| 401 |
eta=(datetime.now() + timedelta(days=1)).isoformat(), |
| 402 |
args=[2, 4, 8], kwargs={}, |
| 403 |
) |
| 404 |
|
| 405 |
c.qos = QoS(c.task_consumer.qos, 1) |
| 406 |
current_pcount = c.qos.value |
| 407 |
c.event_dispatcher.enabled = False |
| 408 |
c.update_strategies() |
| 409 |
callback = self._get_on_message(c) |
| 410 |
callback(m) |
| 411 |
c.timer.stop() |
| 412 |
c.timer.join(1) |
| 413 |
|
| 414 |
items = [entry[2] for entry in self.timer.queue] |
| 415 |
found = 0 |
| 416 |
for item in items: |
| 417 |
if item.args[0].name == self.foo_task.name: |
| 418 |
found = True |
| 419 |
assert found |
| 420 |
assert c.qos.value > current_pcount |
| 421 |
c.timer.stop() |
| 422 |
|
| 423 |
def test_pidbox_callback(self): |
| 424 |
c = self.NoopConsumer() |
| 425 |
con = find_step(c, consumer.Control).box |
| 426 |
con.node = Mock() |
| 427 |
con.reset = Mock() |
| 428 |
|
| 429 |
con.on_message('foo', 'bar') |
| 430 |
con.node.handle_message.assert_called_with('foo', 'bar') |
| 431 |
|
| 432 |
con.node = Mock() |
| 433 |
con.node.handle_message.side_effect = KeyError('foo') |
| 434 |
con.on_message('foo', 'bar') |
| 435 |
con.node.handle_message.assert_called_with('foo', 'bar') |
| 436 |
|
| 437 |
con.node = Mock() |
| 438 |
con.node.handle_message.side_effect = ValueError('foo') |
| 439 |
con.on_message('foo', 'bar') |
| 440 |
con.node.handle_message.assert_called_with('foo', 'bar') |
| 441 |
con.reset.assert_called() |
| 442 |
|
| 443 |
def test_revoke(self): |
| 444 |
c = self.LoopConsumer() |
| 445 |
c.blueprint.state = RUN |
| 446 |
c.steps.pop() |
| 447 |
channel = Mock(name='channel') |
| 448 |
id = uuid() |
| 449 |
t = self.create_task_message( |
| 450 |
channel, self.foo_task.name, |
| 451 |
args=[2, 4, 8], kwargs={}, id=id, |
| 452 |
) |
| 453 |
|
| 454 |
state.revoked.add(id) |
| 455 |
|
| 456 |
callback = self._get_on_message(c) |
| 457 |
callback(t) |
| 458 |
assert self.buffer.empty() |
| 459 |
|
| 460 |
def test_receieve_message_not_registered(self): |
| 461 |
c = self.LoopConsumer() |
| 462 |
c.blueprint.state = RUN |
| 463 |
c.steps.pop() |
| 464 |
channel = Mock(name='channel') |
| 465 |
m = self.create_task_message( |
| 466 |
channel, 'x.X.31x', args=[2, 4, 8], kwargs={}, |
| 467 |
) |
| 468 |
|
| 469 |
callback = self._get_on_message(c) |
| 470 |
assert not callback(m) |
| 471 |
with pytest.raises(Empty): |
| 472 |
self.buffer.get_nowait() |
| 473 |
assert self.timer.empty() |
| 474 |
|
| 475 |
@patch('celery.worker.consumer.consumer.warn') |
| 476 |
@patch('celery.worker.consumer.consumer.logger') |
| 477 |
def test_receieve_message_ack_raises(self, logger, warn): |
| 478 |
c = self.LoopConsumer() |
| 479 |
c.blueprint.state = RUN |
| 480 |
channel = Mock(name='channel') |
| 481 |
m = self.create_task_message( |
| 482 |
channel, self.foo_task.name, |
| 483 |
args=[2, 4, 8], kwargs={}, |
| 484 |
) |
| 485 |
m.headers = None |
| 486 |
|
| 487 |
c.update_strategies() |
| 488 |
c.connection_errors = (socket.error,) |
| 489 |
m.reject = Mock() |
| 490 |
m.reject.side_effect = socket.error('foo') |
| 491 |
callback = self._get_on_message(c) |
| 492 |
assert not callback(m) |
| 493 |
warn.assert_called() |
| 494 |
with pytest.raises(Empty): |
| 495 |
self.buffer.get_nowait() |
| 496 |
assert self.timer.empty() |
| 497 |
m.reject_log_error.assert_called_with(logger, c.connection_errors) |
| 498 |
|
| 499 |
def test_receive_message_eta(self): |
| 500 |
if os.environ.get('C_DEBUG_TEST'): |
| 501 |
pp = partial(print, file=sys.__stderr__) |
| 502 |
else: |
| 503 |
def pp(*args, **kwargs): |
| 504 |
pass |
| 505 |
pp('TEST RECEIVE MESSAGE ETA') |
| 506 |
pp('+CREATE MYKOMBUCONSUMER') |
| 507 |
c = self.LoopConsumer() |
| 508 |
pp('-CREATE MYKOMBUCONSUMER') |
| 509 |
c.steps.pop() |
| 510 |
channel = Mock(name='channel') |
| 511 |
pp('+ CREATE MESSAGE') |
| 512 |
m = self.create_task_message( |
| 513 |
channel, self.foo_task.name, |
| 514 |
args=[2, 4, 8], kwargs={}, |
| 515 |
eta=(datetime.now() + timedelta(days=1)).isoformat(), |
| 516 |
) |
| 517 |
pp('- CREATE MESSAGE') |
| 518 |
|
| 519 |
try: |
| 520 |
pp('+ BLUEPRINT START 1') |
| 521 |
c.blueprint.start(c) |
| 522 |
pp('- BLUEPRINT START 1') |
| 523 |
p = c.app.conf.broker_connection_retry |
| 524 |
c.app.conf.broker_connection_retry = False |
| 525 |
pp('+ BLUEPRINT START 2') |
| 526 |
c.blueprint.start(c) |
| 527 |
pp('- BLUEPRINT START 2') |
| 528 |
c.app.conf.broker_connection_retry = p |
| 529 |
pp('+ BLUEPRINT RESTART') |
| 530 |
c.blueprint.restart(c) |
| 531 |
pp('- BLUEPRINT RESTART') |
| 532 |
pp('+ GET ON MESSAGE') |
| 533 |
callback = self._get_on_message(c) |
| 534 |
pp('- GET ON MESSAGE') |
| 535 |
pp('+ CALLBACK') |
| 536 |
callback(m) |
| 537 |
pp('- CALLBACK') |
| 538 |
finally: |
| 539 |
pp('+ STOP TIMER') |
| 540 |
c.timer.stop() |
| 541 |
pp('- STOP TIMER') |
| 542 |
try: |
| 543 |
pp('+ JOIN TIMER') |
| 544 |
c.timer.join() |
| 545 |
pp('- JOIN TIMER') |
| 546 |
except RuntimeError: |
| 547 |
pass |
| 548 |
|
| 549 |
in_hold = c.timer.queue[0] |
| 550 |
assert len(in_hold) == 3 |
| 551 |
eta, priority, entry = in_hold |
| 552 |
task = entry.args[0] |
| 553 |
assert isinstance(task, Request) |
| 554 |
assert task.name == self.foo_task.name |
| 555 |
assert task.execute() == 2 * 4 * 8 |
| 556 |
with pytest.raises(Empty): |
| 557 |
self.buffer.get_nowait() |
| 558 |
|
| 559 |
def test_reset_pidbox_node(self): |
| 560 |
c = self.NoopConsumer() |
| 561 |
con = find_step(c, consumer.Control).box |
| 562 |
con.node = Mock() |
| 563 |
chan = con.node.channel = Mock() |
| 564 |
chan.close.side_effect = socket.error('foo') |
| 565 |
c.connection_errors = (socket.error,) |
| 566 |
con.reset() |
| 567 |
chan.close.assert_called_with() |
| 568 |
|
| 569 |
def test_reset_pidbox_node_green(self): |
| 570 |
c = self.NoopConsumer(pool=Mock(is_green=True)) |
| 571 |
con = find_step(c, consumer.Control) |
| 572 |
assert isinstance(con.box, gPidbox) |
| 573 |
con.start(c) |
| 574 |
c.pool.spawn_n.assert_called_with(con.box.loop, c) |
| 575 |
|
| 576 |
def test_green_pidbox_node(self): |
| 577 |
pool = Mock() |
| 578 |
pool.is_green = True |
| 579 |
c = self.NoopConsumer(pool=Mock(is_green=True)) |
| 580 |
controller = find_step(c, consumer.Control) |
| 581 |
|
| 582 |
class BConsumer(Mock): |
| 583 |
|
| 584 |
def __enter__(self): |
| 585 |
self.consume() |
| 586 |
return self |
| 587 |
|
| 588 |
def __exit__(self, *exc_info): |
| 589 |
self.cancel() |
| 590 |
|
| 591 |
controller.box.node.listen = BConsumer() |
| 592 |
connections = [] |
| 593 |
|
| 594 |
class Connection: |
| 595 |
calls = 0 |
| 596 |
|
| 597 |
def __init__(self, obj): |
| 598 |
connections.append(self) |
| 599 |
self.obj = obj |
| 600 |
self.default_channel = self.channel() |
| 601 |
self.closed = False |
| 602 |
|
| 603 |
def __enter__(self): |
| 604 |
return self |
| 605 |
|
| 606 |
def __exit__(self, *exc_info): |
| 607 |
self.close() |
| 608 |
|
| 609 |
def channel(self): |
| 610 |
return Mock() |
| 611 |
|
| 612 |
def as_uri(self): |
| 613 |
return 'dummy://' |
| 614 |
|
| 615 |
def drain_events(self, **kwargs): |
| 616 |
if not self.calls: |
| 617 |
self.calls += 1 |
| 618 |
raise socket.timeout() |
| 619 |
self.obj.connection = None |
| 620 |
controller.box._node_shutdown.set() |
| 621 |
|
| 622 |
def close(self): |
| 623 |
self.closed = True |
| 624 |
|
| 625 |
c.connection_for_read = lambda: Connection(obj=c) |
| 626 |
controller = find_step(c, consumer.Control) |
| 627 |
controller.box.loop(c) |
| 628 |
|
| 629 |
controller.box.node.listen.assert_called() |
| 630 |
assert controller.box.consumer |
| 631 |
controller.box.consumer.consume.assert_called_with() |
| 632 |
|
| 633 |
assert c.connection is None |
| 634 |
assert connections[0].closed |
| 635 |
|
| 636 |
@patch('kombu.connection.Connection._establish_connection') |
| 637 |
@patch('kombu.utils.functional.sleep') |
| 638 |
def test_connect_errback(self, sleep, connect): |
| 639 |
def connect_side_effect(): |
| 640 |
yield Mock() |
| 641 |
while True: |
| 642 |
yield ChannelError('error') |
| 643 |
|
| 644 |
c = self.NoopConsumer() |
| 645 |
Transport.connection_errors = (ChannelError,) |
| 646 |
connect.side_effect = connect_side_effect() |
| 647 |
c.connect() |
| 648 |
connect.assert_called_with() |
| 649 |
|
| 650 |
def test_stop_pidbox_node(self): |
| 651 |
c = self.NoopConsumer() |
| 652 |
cont = find_step(c, consumer.Control) |
| 653 |
cont._node_stopped = Event() |
| 654 |
cont._node_shutdown = Event() |
| 655 |
cont._node_stopped.set() |
| 656 |
cont.stop(c) |
| 657 |
|
| 658 |
def test_start__loop(self): |
| 659 |
|
| 660 |
class _QoS: |
| 661 |
prev = 3 |
| 662 |
value = 4 |
| 663 |
|
| 664 |
def update(self): |
| 665 |
self.prev = self.value |
| 666 |
|
| 667 |
init_callback = Mock(name='init_callback') |
| 668 |
c = self.NoopConsumer(init_callback=init_callback) |
| 669 |
c.qos = _QoS() |
| 670 |
c.connection = Connection(self.app.conf.broker_url) |
| 671 |
c.connection.get_heartbeat_interval = Mock(return_value=None) |
| 672 |
c.iterations = 0 |
| 673 |
|
| 674 |
def raises_KeyError(*args, **kwargs): |
| 675 |
c.iterations += 1 |
| 676 |
if c.qos.prev != c.qos.value: |
| 677 |
c.qos.update() |
| 678 |
if c.iterations >= 2: |
| 679 |
raise KeyError('foo') |
| 680 |
|
| 681 |
c.loop = raises_KeyError |
| 682 |
with pytest.raises(KeyError): |
| 683 |
c.start() |
| 684 |
assert c.iterations == 2 |
| 685 |
assert c.qos.prev == c.qos.value |
| 686 |
|
| 687 |
init_callback.reset_mock() |
| 688 |
c = self.NoopConsumer(task_events=False, init_callback=init_callback) |
| 689 |
c.qos = _QoS() |
| 690 |
c.connection = Connection(self.app.conf.broker_url) |
| 691 |
c.connection.get_heartbeat_interval = Mock(return_value=None) |
| 692 |
c.loop = Mock(side_effect=socket.error('foo')) |
| 693 |
with pytest.raises(socket.error): |
| 694 |
c.start() |
| 695 |
c.loop.assert_called() |
| 696 |
|
| 697 |
def test_reset_connection_with_no_node(self): |
| 698 |
c = self.NoopConsumer() |
| 699 |
c.steps.pop() |
| 700 |
c.blueprint.start(c) |
| 701 |
|
| 702 |
|
| 703 |
class test_WorkController(ConsumerCase): |
| 704 |
|
| 705 |
def setup_method(self): |
| 706 |
self.worker = self.create_worker() |
| 707 |
self._logger = worker_module.logger |
| 708 |
self._comp_logger = components.logger |
| 709 |
self.logger = worker_module.logger = Mock() |
| 710 |
self.comp_logger = components.logger = Mock() |
| 711 |
|
| 712 |
@self.app.task(shared=False) |
| 713 |
def foo_task(x, y, z): |
| 714 |
return x * y * z |
| 715 |
self.foo_task = foo_task |
| 716 |
|
| 717 |
def teardown_method(self): |
| 718 |
worker_module.logger = self._logger |
| 719 |
components.logger = self._comp_logger |
| 720 |
|
| 721 |
def create_worker(self, **kw): |
| 722 |
worker = self.app.WorkController(concurrency=1, loglevel=0, **kw) |
| 723 |
worker.blueprint.shutdown_complete.set() |
| 724 |
return worker |
| 725 |
|
| 726 |
def test_on_consumer_ready(self): |
| 727 |
self.worker.on_consumer_ready(Mock()) |
| 728 |
|
| 729 |
def test_setup_queues_worker_direct(self): |
| 730 |
self.app.conf.worker_direct = True |
| 731 |
self.app.amqp.__dict__['queues'] = Mock() |
| 732 |
self.worker.setup_queues({}) |
| 733 |
self.app.amqp.queues.select_add.assert_called_with( |
| 734 |
worker_direct(self.worker.hostname), |
| 735 |
) |
| 736 |
|
| 737 |
def test_setup_queues__missing_queue(self): |
| 738 |
self.app.amqp.queues.select = Mock(name='select') |
| 739 |
self.app.amqp.queues.deselect = Mock(name='deselect') |
| 740 |
self.app.amqp.queues.select.side_effect = KeyError() |
| 741 |
self.app.amqp.queues.deselect.side_effect = KeyError() |
| 742 |
with pytest.raises(ImproperlyConfigured): |
| 743 |
self.worker.setup_queues('x,y', exclude='foo,bar') |
| 744 |
self.app.amqp.queues.select = Mock(name='select') |
| 745 |
with pytest.raises(ImproperlyConfigured): |
| 746 |
self.worker.setup_queues('x,y', exclude='foo,bar') |
| 747 |
|
| 748 |
def test_send_worker_shutdown(self): |
| 749 |
with patch('celery.signals.worker_shutdown') as ws: |
| 750 |
self.worker._send_worker_shutdown() |
| 751 |
ws.send.assert_called_with(sender=self.worker) |
| 752 |
|
| 753 |
@pytest.mark.skip('TODO: unstable test') |
| 754 |
def test_process_shutdown_on_worker_shutdown(self): |
| 755 |
from celery.concurrency.asynpool import Worker |
| 756 |
from celery.concurrency.prefork import process_destructor |
| 757 |
with patch('celery.signals.worker_process_shutdown') as ws: |
| 758 |
with patch('os._exit') as _exit: |
| 759 |
worker = Worker(None, None, on_exit=process_destructor) |
| 760 |
worker._do_exit(22, 3.1415926) |
| 761 |
ws.send.assert_called_with( |
| 762 |
sender=None, pid=22, exitcode=3.1415926, |
| 763 |
) |
| 764 |
_exit.assert_called_with(3.1415926) |
| 765 |
|
| 766 |
def test_process_task_revoked_release_semaphore(self): |
| 767 |
self.worker._quick_release = Mock() |
| 768 |
req = Mock() |
| 769 |
req.execute_using_pool.side_effect = TaskRevokedError |
| 770 |
self.worker._process_task(req) |
| 771 |
self.worker._quick_release.assert_called_with() |
| 772 |
|
| 773 |
delattr(self.worker, '_quick_release') |
| 774 |
self.worker._process_task(req) |
| 775 |
|
| 776 |
def test_shutdown_no_blueprint(self): |
| 777 |
self.worker.blueprint = None |
| 778 |
self.worker._shutdown() |
| 779 |
|
| 780 |
@patch('celery.worker.worker.create_pidlock') |
| 781 |
def test_use_pidfile(self, create_pidlock): |
| 782 |
create_pidlock.return_value = Mock() |
| 783 |
worker = self.create_worker(pidfile='pidfilelockfilepid') |
| 784 |
worker.steps = [] |
| 785 |
worker.start() |
| 786 |
create_pidlock.assert_called() |
| 787 |
worker.stop() |
| 788 |
worker.pidlock.release.assert_called() |
| 789 |
|
| 790 |
def test_attrs(self): |
| 791 |
worker = self.worker |
| 792 |
assert worker.timer is not None |
| 793 |
assert isinstance(worker.timer, Timer) |
| 794 |
assert worker.pool is not None |
| 795 |
assert worker.consumer is not None |
| 796 |
assert worker.steps |
| 797 |
|
| 798 |
def test_with_embedded_beat(self): |
| 799 |
worker = self.app.WorkController(concurrency=1, loglevel=0, beat=True) |
| 800 |
assert worker.beat |
| 801 |
assert worker.beat in [w.obj for w in worker.steps] |
| 802 |
|
| 803 |
def test_with_autoscaler(self): |
| 804 |
worker = self.create_worker( |
| 805 |
autoscale=[10, 3], send_events=False, |
| 806 |
timer_cls='celery.utils.timer2.Timer', |
| 807 |
) |
| 808 |
assert worker.autoscaler |
| 809 |
|
| 810 |
@t.skip.if_win32 |
| 811 |
@pytest.mark.sleepdeprived_patched_module(autoscale) |
| 812 |
def test_with_autoscaler_file_descriptor_safety(self, sleepdeprived): |
| 813 |
# Given: a test celery worker instance with auto scaling |
| 814 |
worker = self.create_worker( |
| 815 |
autoscale=[10, 5], use_eventloop=True, |
| 816 |
timer_cls='celery.utils.timer2.Timer', |
| 817 |
threads=False, |
| 818 |
) |
| 819 |
# Given: This test requires a QoS defined on the worker consumer |
| 820 |
worker.consumer.qos = qos = QoS(lambda prefetch_count: prefetch_count, 2) |
| 821 |
qos.update() |
| 822 |
|
| 823 |
# Given: We have started the worker pool |
| 824 |
worker.pool.start() |
| 825 |
|
| 826 |
# Then: the worker pool is the same as the autoscaler pool |
| 827 |
auto_scaler = worker.autoscaler |
| 828 |
assert worker.pool == auto_scaler.pool |
| 829 |
|
| 830 |
# Given: Utilize kombu to get the global hub state |
| 831 |
hub = get_event_loop() |
| 832 |
# Given: Initial call the Async Pool to register events works fine |
| 833 |
worker.pool.register_with_event_loop(hub) |
| 834 |
|
| 835 |
# Create some mock queue message and read from them |
| 836 |
_keep = [Mock(name=f'req{i}') for i in range(20)] |
| 837 |
[state.task_reserved(m) for m in _keep] |
| 838 |
auto_scaler.body() |
| 839 |
|
| 840 |
# Simulate a file descriptor from the list is closed by the OS |
| 841 |
# auto_scaler.force_scale_down(5) |
| 842 |
# This actually works -- it releases the semaphore properly |
| 843 |
# Same with calling .terminate() on the process directly |
| 844 |
for fd, proc in worker.pool._pool._fileno_to_outq.items(): |
| 845 |
# however opening this fd as a file and closing it will do it |
| 846 |
queue_worker_socket = open(str(fd), "w") |
| 847 |
queue_worker_socket.close() |
| 848 |
break # Only need to do this once |
| 849 |
|
| 850 |
# When: Calling again to register with event loop ... |
| 851 |
worker.pool.register_with_event_loop(hub) |
| 852 |
|
| 853 |
# Then: test did not raise "OSError: [Errno 9] Bad file descriptor!" |
| 854 |
|
| 855 |
# Finally: Clean up so the threads before/after fixture passes |
| 856 |
worker.terminate() |
| 857 |
worker.pool.terminate() |
| 858 |
|
| 859 |
@t.skip.if_win32 |
| 860 |
@pytest.mark.sleepdeprived_patched_module(autoscale) |
| 861 |
def test_with_file_descriptor_safety(self, sleepdeprived): |
| 862 |
# Given: a test celery worker instance |
| 863 |
worker = self.create_worker( |
| 864 |
autoscale=[10, 5], use_eventloop=True, |
| 865 |
timer_cls='celery.utils.timer2.Timer', |
| 866 |
threads=False, |
| 867 |
) |
| 868 |
|
| 869 |
# Given: This test requires a QoS defined on the worker consumer |
| 870 |
worker.consumer.qos = qos = QoS(lambda prefetch_count: prefetch_count, 2) |
| 871 |
qos.update() |
| 872 |
|
| 873 |
# Given: We have started the worker pool |
| 874 |
worker.pool.start() |
| 875 |
|
| 876 |
# Given: Utilize kombu to get the global hub state |
| 877 |
hub = get_event_loop() |
| 878 |
# Given: Initial call the Async Pool to register events works fine |
| 879 |
worker.pool.register_with_event_loop(hub) |
| 880 |
|
| 881 |
# Given: Mock the Hub to return errors for add and remove |
| 882 |
def throw_file_not_found_error(*args, **kwargs): |
| 883 |
raise OSError() |
| 884 |
|
| 885 |
hub.add = throw_file_not_found_error |
| 886 |
hub.add_reader = throw_file_not_found_error |
| 887 |
hub.remove = throw_file_not_found_error |
| 888 |
|
| 889 |
# When: Calling again to register with event loop ... |
| 890 |
worker.pool.register_with_event_loop(hub) |
| 891 |
worker.pool._pool.register_with_event_loop(hub) |
| 892 |
# Then: test did not raise OSError |
| 893 |
# Note: worker.pool is prefork.TaskPool whereas |
| 894 |
# worker.pool._pool is the asynpool.AsynPool class. |
| 895 |
|
| 896 |
# When: Calling the tic method on_poll_start |
| 897 |
worker.pool._pool.on_poll_start() |
| 898 |
# Then: test did not raise OSError |
| 899 |
|
| 900 |
# Given: a mock object that fakes what's required to do what's next |
| 901 |
proc = Mock(_sentinel_poll=42) |
| 902 |
|
| 903 |
# When: Calling again to register with event loop ... |
| 904 |
worker.pool._pool._track_child_process(proc, hub) |
| 905 |
# Then: test did not raise OSError |
| 906 |
|
| 907 |
# Given: |
| 908 |
worker.pool._pool._flush_outqueue = throw_file_not_found_error |
| 909 |
|
| 910 |
# Finally: Clean up so the threads before/after fixture passes |
| 911 |
worker.terminate() |
| 912 |
worker.pool.terminate() |
| 913 |
|
| 914 |
def test_dont_stop_or_terminate(self): |
| 915 |
worker = self.app.WorkController(concurrency=1, loglevel=0) |
| 916 |
worker.stop() |
| 917 |
assert worker.blueprint.state != CLOSE |
| 918 |
worker.terminate() |
| 919 |
assert worker.blueprint.state != CLOSE |
| 920 |
|
| 921 |
sigsafe, worker.pool.signal_safe = worker.pool.signal_safe, False |
| 922 |
try: |
| 923 |
worker.blueprint.state = RUN |
| 924 |
worker.stop(in_sighandler=True) |
| 925 |
assert worker.blueprint.state != CLOSE |
| 926 |
worker.terminate(in_sighandler=True) |
| 927 |
assert worker.blueprint.state != CLOSE |
| 928 |
finally: |
| 929 |
worker.pool.signal_safe = sigsafe |
| 930 |
|
| 931 |
def test_on_timer_error(self): |
| 932 |
worker = self.app.WorkController(concurrency=1, loglevel=0) |
| 933 |
|
| 934 |
try: |
| 935 |
raise KeyError('foo') |
| 936 |
except KeyError as exc: |
| 937 |
components.Timer(worker).on_timer_error(exc) |
| 938 |
msg, args = self.comp_logger.error.call_args[0] |
| 939 |
assert 'KeyError' in msg % args |
| 940 |
|
| 941 |
def test_on_timer_tick(self): |
| 942 |
worker = self.app.WorkController(concurrency=1, loglevel=10) |
| 943 |
|
| 944 |
components.Timer(worker).on_timer_tick(30.0) |
| 945 |
xargs = self.comp_logger.debug.call_args[0] |
| 946 |
fmt, arg = xargs[0], xargs[1] |
| 947 |
assert arg == 30.0 |
| 948 |
assert 'Next ETA %s secs' in fmt |
| 949 |
|
| 950 |
def test_process_task(self): |
| 951 |
worker = self.worker |
| 952 |
worker.pool = Mock() |
| 953 |
channel = Mock() |
| 954 |
m = self.create_task_message( |
| 955 |
channel, self.foo_task.name, |
| 956 |
args=[4, 8, 10], kwargs={}, |
| 957 |
) |
| 958 |
task = Request(m, app=self.app) |
| 959 |
worker._process_task(task) |
| 960 |
assert worker.pool.apply_async.call_count == 1 |
| 961 |
worker.pool.stop() |
| 962 |
|
| 963 |
def test_process_task_raise_base(self): |
| 964 |
worker = self.worker |
| 965 |
worker.pool = Mock() |
| 966 |
worker.pool.apply_async.side_effect = KeyboardInterrupt('Ctrl+C') |
| 967 |
channel = Mock() |
| 968 |
m = self.create_task_message( |
| 969 |
channel, self.foo_task.name, |
| 970 |
args=[4, 8, 10], kwargs={}, |
| 971 |
) |
| 972 |
task = Request(m, app=self.app) |
| 973 |
worker.steps = [] |
| 974 |
worker.blueprint.state = RUN |
| 975 |
with pytest.raises(KeyboardInterrupt): |
| 976 |
worker._process_task(task) |
| 977 |
|
| 978 |
def test_process_task_raise_WorkerTerminate(self): |
| 979 |
worker = self.worker |
| 980 |
worker.pool = Mock() |
| 981 |
worker.pool.apply_async.side_effect = WorkerTerminate() |
| 982 |
channel = Mock() |
| 983 |
m = self.create_task_message( |
| 984 |
channel, self.foo_task.name, |
| 985 |
args=[4, 8, 10], kwargs={}, |
| 986 |
) |
| 987 |
task = Request(m, app=self.app) |
| 988 |
worker.steps = [] |
| 989 |
worker.blueprint.state = RUN |
| 990 |
with pytest.raises(SystemExit): |
| 991 |
worker._process_task(task) |
| 992 |
|
| 993 |
def test_process_task_raise_regular(self): |
| 994 |
worker = self.worker |
| 995 |
worker.pool = Mock() |
| 996 |
worker.pool.apply_async.side_effect = KeyError('some exception') |
| 997 |
channel = Mock() |
| 998 |
m = self.create_task_message( |
| 999 |
channel, self.foo_task.name, |
| 1000 |
args=[4, 8, 10], kwargs={}, |
| 1001 |
) |
| 1002 |
task = Request(m, app=self.app) |
| 1003 |
with pytest.raises(KeyError): |
| 1004 |
worker._process_task(task) |
| 1005 |
worker.pool.stop() |
| 1006 |
|
| 1007 |
def test_start_catches_base_exceptions(self): |
| 1008 |
worker1 = self.create_worker() |
| 1009 |
worker1.blueprint.state = RUN |
| 1010 |
stc = MockStep() |
| 1011 |
stc.start.side_effect = WorkerTerminate() |
| 1012 |
worker1.steps = [stc] |
| 1013 |
worker1.start() |
| 1014 |
stc.start.assert_called_with(worker1) |
| 1015 |
assert stc.terminate.call_count |
| 1016 |
|
| 1017 |
worker2 = self.create_worker() |
| 1018 |
worker2.blueprint.state = RUN |
| 1019 |
sec = MockStep() |
| 1020 |
sec.start.side_effect = WorkerShutdown() |
| 1021 |
sec.terminate = None |
| 1022 |
worker2.steps = [sec] |
| 1023 |
worker2.start() |
| 1024 |
assert sec.stop.call_count |
| 1025 |
|
| 1026 |
def test_statedb(self): |
| 1027 |
from celery.worker import state |
| 1028 |
Persistent = state.Persistent |
| 1029 |
|
| 1030 |
state.Persistent = Mock() |
| 1031 |
try: |
| 1032 |
worker = self.create_worker(statedb='statefilename') |
| 1033 |
assert worker._persistence |
| 1034 |
finally: |
| 1035 |
state.Persistent = Persistent |
| 1036 |
|
| 1037 |
def test_process_task_sem(self): |
| 1038 |
worker = self.worker |
| 1039 |
worker._quick_acquire = Mock() |
| 1040 |
|
| 1041 |
req = Mock() |
| 1042 |
worker._process_task_sem(req) |
| 1043 |
worker._quick_acquire.assert_called_with(worker._process_task, req) |
| 1044 |
|
| 1045 |
def test_signal_consumer_close(self): |
| 1046 |
worker = self.worker |
| 1047 |
worker.consumer = Mock() |
| 1048 |
|
| 1049 |
worker.signal_consumer_close() |
| 1050 |
worker.consumer.close.assert_called_with() |
| 1051 |
|
| 1052 |
worker.consumer.close.side_effect = AttributeError() |
| 1053 |
worker.signal_consumer_close() |
| 1054 |
|
| 1055 |
def test_rusage__no_resource(self): |
| 1056 |
from celery.worker import worker |
| 1057 |
prev, worker.resource = worker.resource, None |
| 1058 |
try: |
| 1059 |
self.worker.pool = Mock(name='pool') |
| 1060 |
with pytest.raises(NotImplementedError): |
| 1061 |
self.worker.rusage() |
| 1062 |
self.worker.stats() |
| 1063 |
finally: |
| 1064 |
worker.resource = prev |
| 1065 |
|
| 1066 |
def test_repr(self): |
| 1067 |
assert repr(self.worker) |
| 1068 |
|
| 1069 |
def test_str(self): |
| 1070 |
assert str(self.worker) == self.worker.hostname |
| 1071 |
|
| 1072 |
def test_start__stop(self): |
| 1073 |
worker = self.worker |
| 1074 |
worker.blueprint.shutdown_complete.set() |
| 1075 |
worker.steps = [MockStep(StartStopStep(self)) for _ in range(4)] |
| 1076 |
worker.blueprint.state = RUN |
| 1077 |
worker.blueprint.started = 4 |
| 1078 |
for w in worker.steps: |
| 1079 |
w.start = Mock() |
| 1080 |
w.close = Mock() |
| 1081 |
w.stop = Mock() |
| 1082 |
|
| 1083 |
worker.start() |
| 1084 |
for w in worker.steps: |
| 1085 |
w.start.assert_called() |
| 1086 |
worker.consumer = Mock() |
| 1087 |
worker.stop(exitcode=3) |
| 1088 |
for stopstep in worker.steps: |
| 1089 |
stopstep.close.assert_called() |
| 1090 |
stopstep.stop.assert_called() |
| 1091 |
|
| 1092 |
# Doesn't close pool if no pool. |
| 1093 |
worker.start() |
| 1094 |
worker.pool = None |
| 1095 |
worker.stop() |
| 1096 |
|
| 1097 |
# test that stop of None is not attempted |
| 1098 |
worker.steps[-1] = None |
| 1099 |
worker.start() |
| 1100 |
worker.stop() |
| 1101 |
|
| 1102 |
def test_start__KeyboardInterrupt(self): |
| 1103 |
worker = self.worker |
| 1104 |
worker.blueprint = Mock(name='blueprint') |
| 1105 |
worker.blueprint.start.side_effect = KeyboardInterrupt() |
| 1106 |
worker.stop = Mock(name='stop') |
| 1107 |
worker.start() |
| 1108 |
worker.stop.assert_called_with(exitcode=EX_FAILURE) |
| 1109 |
|
| 1110 |
def test_register_with_event_loop(self): |
| 1111 |
worker = self.worker |
| 1112 |
hub = Mock(name='hub') |
| 1113 |
worker.blueprint = Mock(name='blueprint') |
| 1114 |
worker.register_with_event_loop(hub) |
| 1115 |
worker.blueprint.send_all.assert_called_with( |
| 1116 |
worker, 'register_with_event_loop', args=(hub,), |
| 1117 |
description='hub.register', |
| 1118 |
) |
| 1119 |
|
| 1120 |
def test_step_raises(self): |
| 1121 |
worker = self.worker |
| 1122 |
step = Mock() |
| 1123 |
worker.steps = [step] |
| 1124 |
step.start.side_effect = TypeError() |
| 1125 |
worker.stop = Mock() |
| 1126 |
worker.start() |
| 1127 |
worker.stop.assert_called_with(exitcode=EX_FAILURE) |
| 1128 |
|
| 1129 |
def test_state(self): |
| 1130 |
assert self.worker.state |
| 1131 |
|
| 1132 |
def test_start__terminate(self): |
| 1133 |
worker = self.worker |
| 1134 |
worker.blueprint.shutdown_complete.set() |
| 1135 |
worker.blueprint.started = 5 |
| 1136 |
worker.blueprint.state = RUN |
| 1137 |
worker.steps = [MockStep() for _ in range(5)] |
| 1138 |
worker.start() |
| 1139 |
for w in worker.steps[:3]: |
| 1140 |
w.start.assert_called() |
| 1141 |
assert worker.blueprint.started == len(worker.steps) |
| 1142 |
assert worker.blueprint.state == RUN |
| 1143 |
worker.terminate() |
| 1144 |
for step in worker.steps: |
| 1145 |
step.terminate.assert_called() |
| 1146 |
worker.blueprint.state = TERMINATE |
| 1147 |
worker.terminate() |
| 1148 |
|
| 1149 |
def test_Hub_create(self): |
| 1150 |
w = Mock() |
| 1151 |
x = components.Hub(w) |
| 1152 |
x.create(w) |
| 1153 |
assert w.timer.max_interval |
| 1154 |
|
| 1155 |
def test_Pool_create_threaded(self): |
| 1156 |
w = Mock() |
| 1157 |
w._conninfo.connection_errors = w._conninfo.channel_errors = () |
| 1158 |
w.pool_cls = Mock() |
| 1159 |
w.use_eventloop = False |
| 1160 |
pool = components.Pool(w) |
| 1161 |
pool.create(w) |
| 1162 |
|
| 1163 |
def test_Pool_pool_no_sem(self): |
| 1164 |
w = Mock() |
| 1165 |
w.pool_cls.uses_semaphore = False |
| 1166 |
components.Pool(w).create(w) |
| 1167 |
assert w.process_task is w._process_task |
| 1168 |
|
| 1169 |
def test_Pool_create(self): |
| 1170 |
from kombu.asynchronous.semaphore import LaxBoundedSemaphore |
| 1171 |
w = Mock() |
| 1172 |
w._conninfo.connection_errors = w._conninfo.channel_errors = () |
| 1173 |
w.hub = Mock() |
| 1174 |
|
| 1175 |
PoolImp = Mock() |
| 1176 |
poolimp = PoolImp.return_value = Mock() |
| 1177 |
poolimp._pool = [Mock(), Mock()] |
| 1178 |
poolimp._cache = {} |
| 1179 |
poolimp._fileno_to_inq = {} |
| 1180 |
poolimp._fileno_to_outq = {} |
| 1181 |
|
| 1182 |
from celery.concurrency.prefork import TaskPool as _TaskPool |
| 1183 |
|
| 1184 |
class MockTaskPool(_TaskPool): |
| 1185 |
Pool = PoolImp |
| 1186 |
|
| 1187 |
@property |
| 1188 |
def timers(self): |
| 1189 |
return {Mock(): 30} |
| 1190 |
|
| 1191 |
w.pool_cls = MockTaskPool |
| 1192 |
w.use_eventloop = True |
| 1193 |
w.consumer.restart_count = -1 |
| 1194 |
pool = components.Pool(w) |
| 1195 |
pool.create(w) |
| 1196 |
pool.register_with_event_loop(w, w.hub) |
| 1197 |
if sys.platform != 'win32': |
| 1198 |
assert isinstance(w.semaphore, LaxBoundedSemaphore) |
| 1199 |
P = w.pool |
| 1200 |
P.start() |
| 1201 |
|
| 1202 |
def test_wait_for_soft_shutdown(self): |
| 1203 |
worker = self.worker |
| 1204 |
worker.app.conf.worker_soft_shutdown_timeout = 10 |
| 1205 |
request = Mock(name='task', id='1234213') |
| 1206 |
state.task_accepted(request) |
| 1207 |
with patch("celery.worker.worker.sleep") as sleep: |
| 1208 |
worker.wait_for_soft_shutdown() |
| 1209 |
sleep.assert_called_with(worker.app.conf.worker_soft_shutdown_timeout) |
| 1210 |
|
| 1211 |
def test_wait_for_soft_shutdown_no_tasks(self): |
| 1212 |
worker = self.worker |
| 1213 |
worker.app.conf.worker_soft_shutdown_timeout = 10 |
| 1214 |
worker.app.conf.worker_enable_soft_shutdown_on_idle = True |
| 1215 |
state.active_requests.clear() |
| 1216 |
with patch("celery.worker.worker.sleep") as sleep: |
| 1217 |
worker.wait_for_soft_shutdown() |
| 1218 |
sleep.assert_called_with(worker.app.conf.worker_soft_shutdown_timeout) |
| 1219 |
|
| 1220 |
def test_wait_for_soft_shutdown_no_wait(self): |
| 1221 |
worker = self.worker |
| 1222 |
request = Mock(name='task', id='1234213') |
| 1223 |
state.task_accepted(request) |
| 1224 |
with patch("celery.worker.worker.sleep") as sleep: |
| 1225 |
worker.wait_for_soft_shutdown() |
| 1226 |
sleep.assert_not_called() |
| 1227 |
|
| 1228 |
def test_wait_for_soft_shutdown_no_wait_no_tasks(self): |
| 1229 |
worker = self.worker |
| 1230 |
worker.app.conf.worker_enable_soft_shutdown_on_idle = True |
| 1231 |
with patch("celery.worker.worker.sleep") as sleep: |
| 1232 |
worker.wait_for_soft_shutdown() |
| 1233 |
sleep.assert_not_called() |
| 1234 |
|
| 1235 |
|
| 1236 |
class test_WorkerApp: |
| 1237 |
|
| 1238 |
def test_safe_say_defaults_to_stderr(self, capfd): |
| 1239 |
safe_say("hello") |
| 1240 |
captured = capfd.readouterr() |
| 1241 |
assert "\nhello\n" == captured.err |
| 1242 |
assert "" == captured.out |
| 1243 |
|
| 1244 |
def test_safe_say_writes_to_std_out(self, capfd): |
| 1245 |
safe_say("out", sys.stdout) |
| 1246 |
captured = capfd.readouterr() |
| 1247 |
assert "\nout\n" == captured.out |
| 1248 |
assert "" == captured.err |
| 1249 |
|
| 1250 |
def test_safe_say_uses_original_os_write(self): |
| 1251 |
from celery import _original_os_write |
| 1252 |
from celery.apps.worker import _original_os_write as worker_os_write |
| 1253 |
|
| 1254 |
assert _original_os_write is not None |
| 1255 |
assert callable(_original_os_write) |
| 1256 |
assert worker_os_write is _original_os_write |
| 1257 |
assert _original_os_write.__name__ == 'write' |
| 1258 |
|
| 1259 |
def test_safe_say_works_with_patched_os_write(self, capfd): |
| 1260 |
original_write = os.write |
| 1261 |
|
| 1262 |
def patched_write(fd, data): |
| 1263 |
raise RuntimeError("do not call blocking functions from the mainloop") |
| 1264 |
|
| 1265 |
try: |
| 1266 |
os.write = patched_write |
| 1267 |
safe_say("test message") |
| 1268 |
captured = capfd.readouterr() |
| 1269 |
assert "\ntest message\n" == captured.err |
| 1270 |
finally: |
| 1271 |
os.write = original_write |