# Path: kuyruk/exceptions.py
# class ResultTimeout(KuyrukError):
#     """
#     Raised from :func:`kuyruk.Task.send_to_queue` if ``wait_result`` is set and
#     reply is not received in ``wait_result`` seconds.
# 
#     """
#     pass
# 
# class RemoteException(KuyrukError):
#     """
#     Raised from :func:`kuyruk.Task.send_to_queue` if ``wait_result`` is set and
#     exception is raised on the worker while running the task.
# 
#     """
#     def __init__(self, type_: Type, value: Exception, traceback: TracebackType) -> None:
#         self.type = type_
#         self.value = value
#         self.traceback = traceback
# 
#     def __str__(self) -> str:
#         return "%s(%r)" % (self.type, self.value)
# 
# Path: tests/tasks.py
# def echo(message):
# def add(a, b):
# def object_result():
# def echo_another(message):
# def flood():
# def raise_exception():
# def discard():
# def retry_task():
# def loop_forever():
# def just_sleep(seconds):
# def eager_task():
# def rejecting_task():
# def sleeping_task(seconds):
# def task_with_signal_handlers(message):
# def function0(sender, task, args, kwargs, description):
# def function2(sender, task, args, kwargs):
# def function5(sender, task, args, kwargs):
# def must_be_called():
# 
# Path: tests/integration/util.py
# @contextmanager
# def run_worker(app='tests.tasks.kuyruk', terminate=True, **kwargs):
#     assert not_running()
#     args = [
#         sys.executable, '-u',
#         '-m', 'kuyruk.__main__',  # run main module
#         '--app', app,
#         'worker',
#         '--logging-level', 'debug',
#     ]
#     for key, value in kwargs.items():
#         args.extend(['--%s' % key.replace('_', '-'), str(value)])
# 
#     environ = os.environ.copy()
#     environ['COVERAGE_PROCESS_START'] = '.coveragerc'
# 
#     popen = What(*args, preexec_fn=os.setsid, env=environ)
#     popen.timeout = TIMEOUT
#     try:
#         yield popen
# 
#         if terminate:
#             # Send SIGTERM to worker for gracefull shutdown
#             popen.terminate()
#             popen.expect("End run worker")
# 
#         popen.expect_exit()
# 
#     finally:
#         # We need to make sure that not any process of kuyruk is running
#         # after the test is finished.
# 
#         # Kill the process and wait until it is dead
#         try:
#             popen.kill()
#             popen.wait()
#         except OSError as e:
#             if e.errno != errno.ESRCH:  # No such process
#                 raise
# 
#         logger.debug('Worker return code: %s', popen.returncode)
# 
#         try:
#             wait_while(lambda: get_pids('kuyruk:'))
#         except KeyboardInterrupt:
#             print(popen.get_output())
#             # Do not raise KeyboardInterrupt here because nose does not print
#             # captured stdout and logging on KeyboardInterrupt
#             raise Exception
# 
# def delete_queue(*queues):
#     """Delete queues from RabbitMQ"""
#     with new_instance().connection() as conn:
#         for name in queues:
#             logger.debug("deleting queue %s", name)
#             with conn.channel() as ch:
#                 ch.queue_delete(queue=name)
# 
# def len_queue(queue):
#     with new_instance().channel() as ch:
#         _, count, _ = ch.queue_declare(queue=queue, durable=True, passive=True, auto_delete=False)
#         return count
# 
# Path: tests/integration/util.py
# def drop_connections(count, timeout):
#     dropped_connections = set()
# 
#     def drop():
#         for conn in _drop_connections():
#             dropped_connections.add(conn)
# 
#         return len(dropped_connections) == count
# 
#     wait_until(drop, timeout)
# 
# def new_instance():
#     config = Config()
#     config.from_pyfile('/tmp/kuyruk_config.py')
#     return Kuyruk(config=config)


import json
import signal
import logging
import unittest
import amqp
from unittest.mock import patch
from kuyruk.exceptions import ResultTimeout, RemoteException
from tests import tasks
from tests.integration.util import run_worker, delete_queue, len_queue
from tests.integration.util import drop_connections, new_instance
        tasks.echo('hello world')
        with run_worker() as worker:
            worker.expect('Consumer started')
            worker.expect('hello world')
            worker.expect('Task is processed')

    def test_import_cache(self):
        """Task is run on default queue"""
        tasks.echo('hello world')
        tasks.echo('hello world')
        with run_worker() as worker:
            worker.expect('Consumer started')
            worker.expect('hello world')
            worker.expect('Task is processed')
            worker.expect('hello world')
            worker.expect('Task is processed')

    def test_another_queue(self):
        """Task is run on another queue"""
        delete_queue('another_queue')
        tasks.echo_another('hello another')
        assert len_queue('another_queue') == 1
        with run_worker(queue='another_queue') as worker:
            worker.expect('Consumer started')
            worker.expect('hello another')
            worker.expect('Task is processed')

    def test_exception(self):
        """Errored task message is discarded"""
        tasks.raise_exception()

# Path: kuyruk/exceptions.py
# class ResultTimeout(KuyrukError):
#     """
#     Raised from :func:`kuyruk.Task.send_to_queue` if ``wait_result`` is set and
#     reply is not received in ``wait_result`` seconds.
# 
#     """
#     pass
# 
# class RemoteException(KuyrukError):
#     """
#     Raised from :func:`kuyruk.Task.send_to_queue` if ``wait_result`` is set and
#     exception is raised on the worker while running the task.
# 
#     """
#     def __init__(self, type_: Type, value: Exception, traceback: TracebackType) -> None:
#         self.type = type_
#         self.value = value
#         self.traceback = traceback
# 
#     def __str__(self) -> str:
#         return "%s(%r)" % (self.type, self.value)
# 
# Path: tests/tasks.py
# def echo(message):
# def add(a, b):
# def object_result():
# def echo_another(message):
# def flood():
# def raise_exception():
# def discard():
# def retry_task():
# def loop_forever():
# def just_sleep(seconds):
# def eager_task():
# def rejecting_task():
# def sleeping_task(seconds):
# def task_with_signal_handlers(message):
# def function0(sender, task, args, kwargs, description):
# def function2(sender, task, args, kwargs):
# def function5(sender, task, args, kwargs):
# def must_be_called():
# 
# Path: tests/integration/util.py
# @contextmanager
# def run_worker(app='tests.tasks.kuyruk', terminate=True, **kwargs):
#     assert not_running()
#     args = [
#         sys.executable, '-u',
#         '-m', 'kuyruk.__main__',  # run main module
#         '--app', app,
#         'worker',
#         '--logging-level', 'debug',
#     ]
#     for key, value in kwargs.items():
#         args.extend(['--%s' % key.replace('_', '-'), str(value)])
# 
#     environ = os.environ.copy()
#     environ['COVERAGE_PROCESS_START'] = '.coveragerc'
# 
#     popen = What(*args, preexec_fn=os.setsid, env=environ)
#     popen.timeout = TIMEOUT
#     try:
#         yield popen
# 
#         if terminate:
#             # Send SIGTERM to worker for gracefull shutdown
#             popen.terminate()
#             popen.expect("End run worker")
# 
#         popen.expect_exit()
# 
#     finally:
#         # We need to make sure that not any process of kuyruk is running
#         # after the test is finished.
# 
#         # Kill the process and wait until it is dead
#         try:
#             popen.kill()
#             popen.wait()
#         except OSError as e:
#             if e.errno != errno.ESRCH:  # No such process
#                 raise
# 
#         logger.debug('Worker return code: %s', popen.returncode)
# 
#         try:
#             wait_while(lambda: get_pids('kuyruk:'))
#         except KeyboardInterrupt:
#             print(popen.get_output())
#             # Do not raise KeyboardInterrupt here because nose does not print
#             # captured stdout and logging on KeyboardInterrupt
#             raise Exception
# 
# def delete_queue(*queues):
#     """Delete queues from RabbitMQ"""
#     with new_instance().connection() as conn:
#         for name in queues:
#             logger.debug("deleting queue %s", name)
#             with conn.channel() as ch:
#                 ch.queue_delete(queue=name)
# 
# def len_queue(queue):
#     with new_instance().channel() as ch:
#         _, count, _ = ch.queue_declare(queue=queue, durable=True, passive=True, auto_delete=False)
#         return count
# 
# Path: tests/integration/util.py
# def drop_connections(count, timeout):
#     dropped_connections = set()
# 
#     def drop():
#         for conn in _drop_connections():
#             dropped_connections.add(conn)
# 
#         return len(dropped_connections) == count
# 
#     wait_until(drop, timeout)
# 
# def new_instance():
#     config = Config()
#     config.from_pyfile('/tmp/kuyruk_config.py')
#     return Kuyruk(config=config)


# Path: tests/integration/test_worker.py
import json
import signal
import logging
import unittest
import amqp
from unittest.mock import patch
from kuyruk.exceptions import ResultTimeout, RemoteException
from tests import tasks
from tests.integration.util import run_worker, delete_queue, len_queue
from tests.integration.util import drop_connections, new_instance

        tasks.echo('hello world')
        with run_worker() as worker:
            worker.expect('Consumer started')
            worker.expect('hello world')
            worker.expect('Task is processed')

    def test_import_cache(self):
        """Task is run on default queue"""
        tasks.echo('hello world')
        tasks.echo('hello world')
        with run_worker() as worker:
            worker.expect('Consumer started')
            worker.expect('hello world')
            worker.expect('Task is processed')
            worker.expect('hello world')
            worker.expect('Task is processed')

    def test_another_queue(self):
        """Task is run on another queue"""
        delete_queue('another_queue')
        tasks.echo_another('hello another')
        assert len_queue('another_queue') == 1
        with run_worker(queue='another_queue') as worker:
            worker.expect('Consumer started')
            worker.expect('hello another')
            worker.expect('Task is processed')

    def test_exception(self):
        """Errored task message is discarded"""
        tasks.raise_exception()

        with run_worker() as worker: