desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Extend to start the actual tests on the channel'
| def begin(self, channel):
| self.fail('AsyncTestCase.begin_test not extended')
|
'close the connection and stop the ioloop'
| def stop(self):
| self.logger.info('Stopping test')
if (self.timeout is not None):
self.connection.remove_timeout(self.timeout)
self.timeout = None
self.connection.close()
|
'called when the connection has finished closing'
| def on_closed(self, connection, reply_code, reply_text):
| self.logger.info('on_closed: %r %r %r', connection, reply_code, reply_text)
self._stop()
|
'called when stuck waiting for connection to close'
| def on_timeout(self):
| self.logger.error('%s timed out; on_timeout called at %s', self, datetime.utcnow())
self.timeout = None
self._timed_out = True
self.stop()
|
'SelectConnection:DefaultPoller'
| def select_default_test(self):
| with mock.patch.multiple(select_connection, SELECT_TYPE=None):
self.start(adapters.SelectConnection)
|
'SelectConnection:select'
| def select_select_test(self):
| with mock.patch.multiple(select_connection, SELECT_TYPE='select'):
self.start(adapters.SelectConnection)
|
'SelectConnection:poll'
| @unittest.skipIf(((not hasattr(select, 'poll')) or (not hasattr(select.poll(), 'modify'))), 'poll not supported')
def select_poll_test(self):
| with mock.patch.multiple(select_connection, SELECT_TYPE='poll'):
self.start(adapters.SelectConnection)
|
'SelectConnection:epoll'
| @unittest.skipIf((not hasattr(select, 'epoll')), 'epoll not supported')
def select_epoll_test(self):
| with mock.patch.multiple(select_connection, SELECT_TYPE='epoll'):
self.start(adapters.SelectConnection)
|
'SelectConnection:kqueue'
| @unittest.skipIf((not hasattr(select, 'kqueue')), 'kqueue not supported')
def select_kqueue_test(self):
| with mock.patch.multiple(select_connection, SELECT_TYPE='kqueue'):
self.start(adapters.SelectConnection)
|
'TornadoConnection'
| def tornado_test(self):
| self.start(adapters.TornadoConnection)
|
'AsyncioConnection'
| @unittest.skipIf((sys.version_info < (3, 4)), 'Asyncio available for Python 3.4+')
def asyncio_test(self):
| self.start(adapters.AsyncioConnection)
|
'LibevConnection'
| @unittest.skipIf((_TARGET == 'PyPy'), 'PyPy is not supported')
@unittest.skipIf((adapters.LibevConnection is None), 'pyev is not installed')
def libev_test(self):
| self.start(adapters.LibevConnection)
|
'called when the connection has finished closing'
| def on_closed(self, connection, reply_code, reply_text):
| self.on_closed_pair = (reply_code, reply_text)
super(TestBlockedConnectionTimesOut, self).on_closed(connection, reply_code, reply_text)
|
'called when the connection has finished closing'
| def on_closed(self, connection, reply_code, reply_text):
| self.on_closed_pair = (reply_code, reply_text)
super(TestBlockedConnectionUnblocks, self).on_closed(connection, reply_code, reply_text)
|
'if connection is closing but closing channels remain, do not call _on_close_ready'
| @mock.patch('pika.connection.Connection._on_close_ready')
def test_on_channel_cleanup_with_closing_channels(self, on_close_ready):
| self.channel.is_open = False
self.channel.is_closing = True
self.channel.is_closed = False
self.connection.close()
self.assertFalse(on_close_ready.called, '_on_close_ready should not have been called')
|
'if connection isn\'t closing _on_close_ready should not be called'
| @mock.patch('pika.connection.Connection._on_close_ready')
def test_on_channel_cleanup_non_closing_state(self, on_close_ready):
| self.connection._on_channel_cleanup(mock.Mock())
self.assertFalse(on_close_ready.called, '_on_close_ready should not have been called')
|
'_on_terminate cleans up heartbeat, adapter, and channels'
| def test_on_terminate_cleans_up(self):
| heartbeat = mock.Mock()
self.connection.heartbeat = heartbeat
self.connection._adapter_disconnect = mock.Mock()
self.connection._on_terminate((-1), 'Undefined')
heartbeat.stop.assert_called_once_with()
self.connection._adapter_disconnect.assert_called_once_with()
self.channel._on_close_meta.... |
'_on_terminate invokes `Connection.ON_CONNECTION_CLOSED` callbacks'
| def test_on_terminate_invokes_connection_closed_callback(self):
| self.connection.callbacks.process = mock.Mock(wraps=self.connection.callbacks.process)
self.connection._adapter_disconnect = mock.Mock()
self.connection._on_terminate(1, 'error text')
self.connection.callbacks.process.assert_called_once_with(0, self.connection.ON_CONNECTION_CLOSED, self.connection, s... |
'_on_terminate invokes `ON_CONNECTION_ERROR` with `IncompatibleProtocolError` and `ON_CONNECTION_CLOSED` callbacks'
| def test_on_terminate_invokes_protocol_on_connection_error_and_closed(self):
| with mock.patch.object(self.connection.callbacks, 'process'):
self.connection._adapter_disconnect = mock.Mock()
self.connection._set_connection_state(self.connection.CONNECTION_PROTOCOL)
self.connection._on_terminate(1, 'error text')
self.assertEqual(self.connection.callbacks.proc... |
'_on_terminate invokes `ON_CONNECTION_ERROR` with `ProbableAuthenticationError` and `ON_CONNECTION_CLOSED` callbacks'
| def test_on_terminate_invokes_auth_on_connection_error_and_closed(self):
| with mock.patch.object(self.connection.callbacks, 'process'):
self.connection._adapter_disconnect = mock.Mock()
self.connection._set_connection_state(self.connection.CONNECTION_START)
self.connection._on_terminate(1, 'error text')
self.assertEqual(self.connection.callbacks.process... |
'_on_terminate invokes `ON_CONNECTION_ERROR` with `ProbableAccessDeniedError` and `ON_CONNECTION_CLOSED` callbacks'
| def test_on_terminate_invokes_access_denied_on_connection_error_and_closed(self):
| with mock.patch.object(self.connection.callbacks, 'process'):
self.connection._adapter_disconnect = mock.Mock()
self.connection._set_connection_state(self.connection.CONNECTION_TUNE)
self.connection._on_terminate(1, 'error text')
self.assertEqual(self.connection.callbacks.process.... |
'_next_channel_number in new conn should always be 1'
| @mock.patch('pika.connection.Connection.connect')
def test_new_conn_should_use_first_channel(self, connect):
| conn = connection.Connection()
self.assertEqual(1, conn._next_channel_number())
|
'_next_channel_number must return lowest available channel number'
| def test_next_channel_number_returns_lowest_unused(self):
| for channel_num in xrange(1, 50):
self.connection._channels[channel_num] = True
expectation = random.randint(5, 49)
del self.connection._channels[expectation]
self.assertEqual(self.connection._next_channel_number(), expectation)
|
'make sure the callback adding works'
| def test_add_callbacks(self):
| self.connection.callbacks = mock.Mock(spec=self.connection.callbacks)
for (test_method, expected_key) in ((self.connection.add_backpressure_callback, self.connection.ON_CONNECTION_BACKPRESSURE), (self.connection.add_on_open_callback, self.connection.ON_CONNECTION_OPEN), (self.connection.add_on_close_callback, s... |
'make sure the add on close callback is added'
| def test_add_on_close_callback(self):
| self.connection.callbacks = mock.Mock(spec=self.connection.callbacks)
self.connection.add_on_open_callback(callback_method)
self.connection.callbacks.add.assert_called_once_with(0, self.connection.ON_CONNECTION_OPEN, callback_method, False)
|
'make sure the add on open error callback is added'
| def test_add_on_open_error_callback(self):
| self.connection.callbacks = mock.Mock(spec=self.connection.callbacks)
self.connection.add_on_open_error_callback(callback_method)
self.connection.callbacks.remove.assert_called_once_with(0, self.connection.ON_CONNECTION_ERROR, self.connection._on_connection_error)
self.connection.callbacks.add.assert_ca... |
'test the channel method'
| def test_channel(self):
| self.connection._next_channel_number = mock.Mock(return_value=42)
test_channel = mock.Mock(spec=channel.Channel)
self.connection._create_channel = mock.Mock(return_value=test_channel)
self.connection._add_channel_callbacks = mock.Mock()
ret_channel = self.connection.channel(callback_method)
self... |
'check that adapter connection with AMQP is not happening in constructor'
| def test_connect_no_adapter_connect_from_constructor(self):
| with mock.patch('pika.connection.Connection._adapter_connect', return_value=Exception('_adapter_connect failed')) as adapter_connect_mock:
with mock.patch('pika.connection.Connection.add_timeout', return_value='timer') as add_timeout_mock:
conn = connection.Connection()
self.asser... |
'make sure client properties has some important keys'
| def test_client_properties(self):
| client_props = self.connection._client_properties
self.assertTrue(isinstance(client_props, dict))
for required_key in ('product', 'platform', 'capabilities', 'information', 'version'):
self.assertTrue((required_key in client_props), ('%s missing' % required_key))
|
'test setting the backpressure multiplier'
| def test_set_backpressure_multiplier(self):
| self.connection._backpressure_multiplier = None
self.connection.set_backpressure_multiplier(value=5)
self.assertEqual(5, self.connection._backpressure_multiplier)
|
'test closing all channels'
| def test_close_channels(self):
| self.connection.connection_state = self.connection.CONNECTION_OPEN
self.connection.callbacks = mock.Mock(spec=self.connection.callbacks)
opening_channel = mock.Mock(is_open=False, is_closed=False, is_closing=False)
open_channel = mock.Mock(is_open=True, is_closed=False, is_closing=False)
closing_cha... |
'make sure the connect method sets the state and sends a frame'
| @mock.patch('pika.frame.ProtocolHeader')
def test_on_connect_timer(self, frame_protocol_header):
| self.connection.connection_state = self.connection.CONNECTION_INIT
self.connection._adapter_connect = mock.Mock(return_value=None)
self.connection._send_frame = mock.Mock()
frame_protocol_header.spec = frame.ProtocolHeader
frame_protocol_header.return_value = 'frame object'
self.connection._o... |
'try the different reconnect logic, check state & other class vars'
| def test_on_connect_timer_reconnect(self):
| self.connection.connection_state = self.connection.CONNECTION_INIT
self.connection._adapter_connect = mock.Mock(return_value='error')
self.connection.callbacks = mock.Mock(spec=self.connection.callbacks)
self.connection.remaining_connection_attempts = 2
self.connection.params.retry_delay = 555
s... |
'make sure starting a connection sets the correct class vars'
| def test_on_connection_start(self):
| method_frame = mock.Mock()
method_frame.method = mock.Mock()
method_frame.method.mechanisms = str(credentials.PlainCredentials.TYPE)
method_frame.method.version_major = 0
method_frame.method.version_minor = 9
method_frame.method.server_properties = {'capabilities': {'basic.nack': True, 'consumer... |
'make sure on connection tune turns the connection params'
| @mock.patch('pika.heartbeat.HeartbeatChecker')
@mock.patch('pika.frame.Method')
def test_on_connection_tune(self, method, heartbeat_checker):
| heartbeat_checker.return_value = 'hearbeat obj'
self.connection._flush_outbound = mock.Mock()
marshal = mock.Mock(return_value='ab')
method.return_value = mock.Mock(marshal=marshal)
self.connection._rpc = mock.Mock()
method_frame = mock.Mock()
method_frame.method = mock.Mock()
method_... |
'make sure connection close sends correct frames'
| def test_on_connection_closed(self):
| method_frame = mock.Mock()
method_frame.method = mock.Mock(spec=spec.Connection.Close)
method_frame.method.reply_code = 1
method_frame.method.reply_text = 'hello'
self.connection._on_terminate = mock.Mock()
self.connection._on_connection_close(method_frame)
self.connection._on_terminate.asse... |
'make sure _on_connection_close_ok terminates connection'
| def test_on_connection_close_ok(self):
| method_frame = mock.Mock()
method_frame.method = mock.Mock(spec=spec.Connection.CloseOk)
self.connection.closing = (1, 'bye')
self.connection._on_terminate = mock.Mock()
self.connection._on_connection_close_ok(method_frame)
self.connection._on_terminate.assert_called_once_with(1, 'bye')
|
'test on data available and process frame'
| @mock.patch('pika.frame.decode_frame')
def test_on_data_available(self, decode_frame):
| data_in = ['data']
self.connection._frame_buffer = ['old_data']
for frame_type in (frame.Method, spec.Basic.Deliver, frame.Heartbeat):
frame_value = mock.Mock(spec=frame_type)
frame_value.frame_type = 2
frame_value.method = 2
frame_value.channel_number = 1
self.connec... |
'Setup timeout handler for detecting \'no-activity\'
and start polling.'
| def start(self):
| fail_timer = self.ioloop.add_timeout(self.TIMEOUT, self.on_timeout)
self.addCleanup(self.ioloop.remove_timeout, fail_timer)
self.ioloop.start()
self.ioloop._poller.activate_poller.assert_called_once_with()
self.ioloop._poller.deactivate_poller.assert_called_once_with()
|
'called when stuck waiting for connection to close'
| def on_timeout(self):
| self.ioloop.stop()
self.fail('Test timed out')
|
'Starts a thread that stops ioloop after a while
and start polling'
| def start_test(self):
| timer = threading.Timer(0.1, self.ioloop.stop)
self.addCleanup(timer.cancel)
timer.start()
self.start()
|
'Set timers that timers that fires in succession with the sepecified
interval.'
| def set_timers(self):
| self.timer_stack = list()
for i in range(self.NUM_TIMERS, 0, (-1)):
deadline = (i * self.TIMER_INTERVAL)
self.ioloop.add_timeout(deadline, partial(self.on_timer, i))
self.timer_stack.append(i)
|
'Set timers and start ioloop.'
| def start_test(self):
| self.set_timers()
self.start()
|
'A timeout handler that verifies that the given parameter matches
what is expected.'
| def on_timer(self, val):
| self.assertEqual(val, self.timer_stack.pop())
if (not self.timer_stack):
self.ioloop.stop()
|
'Setup 5 timeout handlers and observe them get invoked one by one.'
| def test_normal(self):
| self.start_test()
|
'Verifies that an attempt to delete a timeout within the
corresponding handler generates no exceptions.'
| def test_timer_for_deleting_itself(self):
| self.timer_stack = list()
handle_holder = []
self.timer_got_fired = False
self.handle = self.ioloop.add_timeout(0.1, partial(self._on_timer_delete_itself, handle_holder))
handle_holder.append(self.handle)
self.start()
self.assertTrue(self.timer_got_called)
|
'A timeout hanlder that tries to remove itself.'
| def _on_timer_delete_itself(self, handle_holder):
| self.assertEqual(self.handle, handle_holder.pop())
self.timer_got_called = True
self.ioloop.remove_timeout(self.handle)
self.ioloop.stop()
|
'Verifies that an attempt by a timeout handler to delete another,
that is ready to run, cancels the execution of the latter without
generating an exception. This should pose no issues.'
| def test_timer_delete_another(self):
| holder_for_target_timer = []
self.ioloop.add_timeout(0.01, partial(self._on_timer_delete_another, holder_for_target_timer))
timer_2 = self.ioloop.add_timeout(0.02, self._on_timer_no_call)
holder_for_target_timer.append(timer_2)
time.sleep(0.03)
self.start()
self.assertTrue(self.deleted_anoth... |
'A timeout handler that tries to remove another timeout handler
that is ready to run. This should pose no issues.'
| def _on_timer_delete_another(self, holder):
| target_timer = holder[0]
self.ioloop.remove_timeout(target_timer)
self.deleted_another_timer = True
def _on_timer_conclude():
'A timeout handler that is called to verify outcome of calling\n or not calling of ... |
'A timeout handler that is used when it\'s assumed not be called.'
| def _on_timer_no_call(self):
| self.fail('deleted timer callback was called.')
|
'Setup timers, sleep and start polling'
| def start_test(self):
| self.set_timers()
time.sleep((self.NUM_TIMERS * self.TIMER_INTERVAL))
self.start()
|
'Store \'sock\' in self.sock_map and return the fileno.'
| def save_sock(self, sock):
| fd_ = sock.fileno()
self.sock_map[fd_] = sock
return fd_
|
'Create a socket and setup \'accept\' handler'
| def create_accept_socket(self):
| listen_sock = socket.socket()
listen_sock.setblocking(0)
listen_sock.bind(('localhost', 0))
listen_sock.listen(1)
fd_ = self.save_sock(listen_sock)
self.listen_addr = listen_sock.getsockname()
self.ioloop.add_handler(fd_, self.do_accept, READ)
|
'Create a pair of socket and setup \'connected\' handler'
| def create_write_socket(self, on_connected):
| write_sock = socket.socket()
write_sock.setblocking(0)
err = write_sock.connect_ex(self.listen_addr)
self.assertIn(err, (errno.EINPROGRESS, errno.EWOULDBLOCK))
fd_ = self.save_sock(write_sock)
self.ioloop.add_handler(fd_, on_connected, WRITE)
return write_sock
|
'Create socket from the given fd_ and setup \'read\' handler'
| def do_accept(self, fd_, events):
| self.assertEqual(events, READ)
listen_sock = self.sock_map[fd_]
(read_sock, _) = listen_sock.accept()
fd_ = self.save_sock(read_sock)
self.ioloop.add_handler(fd_, self.do_read, READ)
|
'Create socket from given _fd and respond to \'connected\'.
Implemenation is subclass\'s responsibility.'
| def connected(self, _fd, _events):
| self.fail('IOLoopSocketBase.connected not extended')
|
'read from fd and check the received content'
| def do_read(self, fd_, events):
| self.assertEqual(events, READ)
self.verify_message(self.sock_map[fd_].recv(self.READ_SIZE))
|
'See if \'msg\' matches what is expected. This is a stub.
Real implementation is subclass\'s responsibility'
| def verify_message(self, _msg):
| self.fail('IOLoopSocketBase.verify_message not extended')
|
'called when stuck waiting for connection to close'
| def on_timeout(self):
| self.ioloop.stop()
self.fail('Test timed out')
|
'Create a pair of sockets and poll'
| def start(self):
| self.create_write_socket(self.connected)
super(IOLoopSimpleMessageTestCaseSelect, self).start()
|
'Respond to \'connected\' event by writing to the write-side.'
| def connected(self, fd, events):
| self.assertEqual(events, WRITE)
self.sock_map[fd].send('X')
self.ioloop.update_handler(fd, 0)
|
'Make sure we get what is expected and stop polling'
| def verify_message(self, msg):
| self.assertEqual(msg, 'X')
self.ioloop.stop()
|
'Simple message Test'
| def start_test(self):
| self.start()
|
'A signal handler that gets called in response to
os.kill(signal.SIGUSR1).'
| @staticmethod
def signal_handler(signum, interrupted_stack):
| pass
|
'Read from within poll loop that gets receives eintr error.'
| def _eintr_read_handler(self, fileno, events):
| self.assertEqual(events, READ)
sock = socket.fromfd(os.dup(fileno), socket.AF_INET, socket.SOCK_STREAM)
self.addCleanup(sock.close)
mesg = sock.recv(256)
self.assertEqual(mesg, self.MSG_CONTENT)
self.poller.stop()
self._eintr_read_handler_is_called = True
|
'This function gets called when eintr-test failed to get
_eintr_read_handler called.'
| def _eintr_test_fail(self):
| self.poller.stop()
self.fail('Eintr-test timed out')
|
'Test that poll() is properly restarted after receiving EINTR error.
Class of an exception raised to signal the error differs in one
implementation of polling mechanism and another.'
| @unittest.skipUnless(pika.compat.HAVE_SIGNAL, "This platform doesn't support posix signals")
@mock.patch('pika.adapters.select_connection._is_resumable')
def test_eintr(self, is_resumable_mock, is_resumable_raw=pika.adapters.select_connection._is_resumable):
| is_resumable_mock.side_effect = is_resumable_raw
self.poller = self.ioloop._get_poller()
sockpair = self.poller._get_interrupt_pair()
self.addCleanup(sockpair[0].close)
self.addCleanup(sockpair[1].close)
self._eintr_read_handler_is_called = False
self.poller.add_handler(sockpair[0].fileno(),... |
':returns: a dict of expected public property names and default values
for `pika.connection.Parameters`'
| def get_default_properties(self):
| kls = connection.Parameters
defaults = {'backpressure_detection': kls.DEFAULT_BACKPRESSURE_DETECTION, 'blocked_connection_timeout': kls.DEFAULT_BLOCKED_CONNECTION_TIMEOUT, 'channel_max': kls.DEFAULT_CHANNEL_MAX, 'client_properties': kls.DEFAULT_CLIENT_PROPERTIES, 'connection_attempts': kls.DEFAULT_CONNECTION_AT... |
'Assert that the given parameters object has the default parameter
values.
:param params: verify that the given params instance has all default
property values
:type params: one of the classes based on `pika.connection.Parameters`'
| def assert_default_parameter_values(self, params):
| for (name, expected_value) in dict_iteritems(self.get_default_properties()):
value = getattr(params, name)
self.assertEqual(value, expected_value, msg=('Expected %s=%r, but got %r' % (name, expected_value, value)))
|
'make sure connection kwargs get set correctly'
| def test_good_connection_parameters(self):
| kwargs = {'backpressure_detection': False, 'blocked_connection_timeout': 10.5, 'channel_max': 3, 'client_properties': {'good': 'day'}, 'connection_attempts': 2, 'credentials': credentials.PlainCredentials('very', 'secure'), 'frame_max': 40000, 'heartbeat': 7, 'host': 'https://www.test.com', 'locale': 'en', 'port': ... |
'test connection kwargs type checks throw errors for bad input'
| def test_bad_type_connection_parameters(self):
| kwargs = {'host': 'https://www.test.com', 'port': 5678, 'virtual_host': 'vvhost', 'channel_max': 3, 'frame_max': 40000, 'heartbeat': 7, 'backpressure_detection': False, 'ssl': True, 'blocked_connection_timeout': 10.5}
for (bad_field, bad_value) in (('host', 15672), ('port', '5672'), ('virtual_host', True), ('ch... |
'test for the different query stings checked by process url'
| def test_good_parameters(self):
| query_args = {'blocked_connection_timeout': 10.5, 'channel_max': 3, 'connection_attempts': 2, 'frame_max': 40000, 'heartbeat': 7, 'locale': 'en_UK', 'retry_delay': 3, 'socket_timeout': 100.5, 'ssl_options': {'ssl': 'options'}}
for backpressure in ('t', 'f'):
test_params = copy.deepcopy(query_args)
... |
'Setup the example publisher object, passing in the URL we will use
to connect to RabbitMQ.
:param str amqp_url: The URL for connecting to RabbitMQ'
| def __init__(self, amqp_url):
| self._connection = None
self._channel = None
self._deliveries = None
self._acked = None
self._nacked = None
self._message_number = None
self._stopping = False
self._url = amqp_url
|
'This method connects to RabbitMQ, returning the connection handle.
When the connection is established, the on_connection_open method
will be invoked by pika. If you want the reconnection to work, make
sure you set stop_ioloop_on_close to False, which is not the default
behavior of this adapter.
:rtype: pika.SelectConn... | def connect(self):
| LOGGER.info('Connecting to %s', self._url)
return pika.SelectConnection(pika.URLParameters(self._url), on_open_callback=self.on_connection_open, on_close_callback=self.on_connection_closed, stop_ioloop_on_close=False)
|
'This method is called by pika once the connection to RabbitMQ has
been established. It passes the handle to the connection object in
case we need it, but in this case, we\'ll just mark it unused.
:type unused_connection: pika.SelectConnection'
| def on_connection_open(self, unused_connection):
| LOGGER.info('Connection opened')
self.open_channel()
|
'This method is invoked by pika when the connection to RabbitMQ is
closed unexpectedly. Since it is unexpected, we will reconnect to
RabbitMQ if it disconnects.
:param pika.connection.Connection connection: The closed connection obj
:param int reply_code: The server provided reply_code if given
:param str reply_text: T... | def on_connection_closed(self, connection, reply_code, reply_text):
| self._channel = None
if self._stopping:
self._connection.ioloop.stop()
else:
LOGGER.warning('Connection closed, reopening in 5 seconds: (%s) %s', reply_code, reply_text)
self._connection.add_timeout(5, self._connection.ioloop.stop)
|
'This method will open a new channel with RabbitMQ by issuing the
Channel.Open RPC command. When RabbitMQ confirms the channel is open
by sending the Channel.OpenOK RPC reply, the on_channel_open method
will be invoked.'
| def open_channel(self):
| LOGGER.info('Creating a new channel')
self._connection.channel(on_open_callback=self.on_channel_open)
|
'This method is invoked by pika when the channel has been opened.
The channel object is passed in so we can make use of it.
Since the channel is now open, we\'ll declare the exchange to use.
:param pika.channel.Channel channel: The channel object'
| def on_channel_open(self, channel):
| LOGGER.info('Channel opened')
self._channel = channel
self.add_on_channel_close_callback()
self.setup_exchange(self.EXCHANGE)
|
'This method tells pika to call the on_channel_closed method if
RabbitMQ unexpectedly closes the channel.'
| def add_on_channel_close_callback(self):
| LOGGER.info('Adding channel close callback')
self._channel.add_on_close_callback(self.on_channel_closed)
|
'Invoked by pika when RabbitMQ unexpectedly closes the channel.
Channels are usually closed if you attempt to do something that
violates the protocol, such as re-declare an exchange or queue with
different parameters. In this case, we\'ll close the connection
to shutdown the object.
:param pika.channel.Channel channel:... | def on_channel_closed(self, channel, reply_code, reply_text):
| LOGGER.warning('Channel was closed: (%s) %s', reply_code, reply_text)
self._channel = None
if (not self._stopping):
self._connection.close()
|
'Setup the exchange on RabbitMQ by invoking the Exchange.Declare RPC
command. When it is complete, the on_exchange_declareok method will
be invoked by pika.
:param str|unicode exchange_name: The name of the exchange to declare'
| def setup_exchange(self, exchange_name):
| LOGGER.info('Declaring exchange %s', exchange_name)
self._channel.exchange_declare(self.on_exchange_declareok, exchange_name, self.EXCHANGE_TYPE)
|
'Invoked by pika when RabbitMQ has finished the Exchange.Declare RPC
command.
:param pika.Frame.Method unused_frame: Exchange.DeclareOk response frame'
| def on_exchange_declareok(self, unused_frame):
| LOGGER.info('Exchange declared')
self.setup_queue(self.QUEUE)
|
'Setup the queue on RabbitMQ by invoking the Queue.Declare RPC
command. When it is complete, the on_queue_declareok method will
be invoked by pika.
:param str|unicode queue_name: The name of the queue to declare.'
| def setup_queue(self, queue_name):
| LOGGER.info('Declaring queue %s', queue_name)
self._channel.queue_declare(self.on_queue_declareok, queue_name)
|
'Method invoked by pika when the Queue.Declare RPC call made in
setup_queue has completed. In this method we will bind the queue
and exchange together with the routing key by issuing the Queue.Bind
RPC command. When this command is complete, the on_bindok method will
be invoked by pika.
:param pika.frame.Method method_... | def on_queue_declareok(self, method_frame):
| LOGGER.info('Binding %s to %s with %s', self.EXCHANGE, self.QUEUE, self.ROUTING_KEY)
self._channel.queue_bind(self.on_bindok, self.QUEUE, self.EXCHANGE, self.ROUTING_KEY)
|
'This method is invoked by pika when it receives the Queue.BindOk
response from RabbitMQ. Since we know we\'re now setup and bound, it\'s
time to start publishing.'
| def on_bindok(self, unused_frame):
| LOGGER.info('Queue bound')
self.start_publishing()
|
'This method will enable delivery confirmations and schedule the
first message to be sent to RabbitMQ'
| def start_publishing(self):
| LOGGER.info('Issuing consumer related RPC commands')
self.enable_delivery_confirmations()
self.schedule_next_message()
|
'Send the Confirm.Select RPC method to RabbitMQ to enable delivery
confirmations on the channel. The only way to turn this off is to close
the channel and create a new one.
When the message is confirmed from RabbitMQ, the
on_delivery_confirmation method will be invoked passing in a Basic.Ack
or Basic.Nack method from R... | def enable_delivery_confirmations(self):
| LOGGER.info('Issuing Confirm.Select RPC command')
self._channel.confirm_delivery(self.on_delivery_confirmation)
|
'Invoked by pika when RabbitMQ responds to a Basic.Publish RPC
command, passing in either a Basic.Ack or Basic.Nack frame with
the delivery tag of the message that was published. The delivery tag
is an integer counter indicating the message number that was sent
on the channel via Basic.Publish. Here we\'re just doing h... | def on_delivery_confirmation(self, method_frame):
| confirmation_type = method_frame.method.NAME.split('.')[1].lower()
LOGGER.info('Received %s for delivery tag: %i', confirmation_type, method_frame.method.delivery_tag)
if (confirmation_type == 'ack'):
self._acked += 1
elif (confirmation_type == 'nack'):
self._nacked += 1
... |
'If we are not closing our connection to RabbitMQ, schedule another
message to be delivered in PUBLISH_INTERVAL seconds.'
| def schedule_next_message(self):
| LOGGER.info('Scheduling next message for %0.1f seconds', self.PUBLISH_INTERVAL)
self._connection.add_timeout(self.PUBLISH_INTERVAL, self.publish_message)
|
'If the class is not stopping, publish a message to RabbitMQ,
appending a list of deliveries with the message number that was sent.
This list will be used to check for delivery confirmations in the
on_delivery_confirmations method.
Once the message has been sent, schedule another message to be sent.
The main reason I p... | def publish_message(self):
| if ((self._channel is None) or (not self._channel.is_open)):
return
hdrs = {u'\u0645\u0641\u062a\u0627\u062d': u' \u0642\u064a\u0645\u0629', u'\u952e': u'\u503c', u'\u30ad\u30fc': u'\u5024'}
properties = pika.BasicProperties(app_id='example-publisher', content_type='application/json', headers=hdr... |
'Run the example code by connecting and then starting the IOLoop.'
| def run(self):
| while (not self._stopping):
self._connection = None
self._deliveries = []
self._acked = 0
self._nacked = 0
self._message_number = 0
try:
self._connection = self.connect()
self._connection.ioloop.start()
except KeyboardInterrupt:
... |
'Stop the example by closing the channel and connection. We
set a flag here so that we stop scheduling new messages to be
published. The IOLoop is started because this method is
invoked by the Try/Catch below when KeyboardInterrupt is caught.
Starting the IOLoop again will allow the publisher to cleanly
disconnect from... | def stop(self):
| LOGGER.info('Stopping')
self._stopping = True
self.close_channel()
self.close_connection()
|
'Invoke this command to close the channel with RabbitMQ by sending
the Channel.Close RPC command.'
| def close_channel(self):
| if (self._channel is not None):
LOGGER.info('Closing the channel')
self._channel.close()
|
'This method closes the connection to RabbitMQ.'
| def close_connection(self):
| if (self._connection is not None):
LOGGER.info('Closing connection')
self._connection.close()
|
'Add an exchange to the list of exchanges to read from.'
| @inlineCallbacks
def read(self, exchange, routing_key, callback):
| if self.connected:
(yield self.setup_read(exchange, routing_key, callback))
|
'This function does the work to read from an exchange.'
| @inlineCallbacks
def setup_read(self, exchange, routing_key, callback):
| if (not (exchange == '')):
(yield self.channel.exchange_declare(exchange=exchange, type='topic', durable=True, auto_delete=False))
self.channel.queue_declare(queue=routing_key, durable=True)
(queue, consumer_tag) = (yield self.channel.basic_consume(queue=routing_key, no_ack=False))
d = queue.get... |
'Callback function which is called when an item is read.'
| def _read_item(self, item, queue, callback):
| d = queue.get()
d.addCallback(self._read_item, queue, callback)
d.addErrback(self._read_item_err)
(channel, deliver, props, msg) = item
log.msg(('%s (%s): %s' % (deliver.exchange, deliver.routing_key, repr(msg))), system='Pika:<=')
d = defer.maybeDeferred(callback, item)
d.addCallbacks... |
'If connected, send all waiting messages.'
| def send(self):
| if self.connected:
while (len(self.factory.queued_messages) > 0):
(exchange, r_key, message) = self.factory.queued_messages.pop(0)
self.send_message(exchange, r_key, message)
|
'Send a single message.'
| @inlineCallbacks
def send_message(self, exchange, routing_key, msg):
| log.msg(('%s (%s): %s' % (exchange, routing_key, repr(msg))), system='Pika:=>')
(yield self.channel.exchange_declare(exchange=exchange, type='topic', durable=True, auto_delete=False))
prop = spec.BasicProperties(delivery_mode=2)
try:
(yield self.channel.basic_publish(exchange=exchange, rou... |
'Configure an exchange to be read from.'
| def read_messages(self, exchange, routing_key, callback):
| self.read_list.append((exchange, routing_key, callback))
if (self.client is not None):
self.client.read(exchange, routing_key, callback)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.