def test_lookup_configs():
    expected_system_type = "deb"

    def make_remote():
        remote = Mock()
        remote.arch = "x86_64"
        remote.os = Mock()
        remote.os.name = "ubuntu"
        remote.os.version = "14.04"
        remote.os.codename = "trusty"
        remote.system_type = expected_system_type
        return remote

    ctx = Mock()

    class cluster:
        remote1 = make_remote()
        remote2 = make_remote()
        remotes = {remote1: ["client.0"], remote2: ["mon.a", "osd.0"]}

        def only(self, role):
            result = Mock()
            if role in ("client.0",):
                result.remotes = {cluster.remote1: None}
            elif role in ("osd.0", "mon.a"):
                result.remotes = {cluster.remote2: None}
            else:
                result.remotes = None
            return result

    ctx.cluster = cluster()
    ctx.config = {"roles": [["client.0"], ["mon.a", "osd.0"]]}

    # nothing -> nothing
    assert buildpackages.lookup_configs(ctx, {}) == []
    assert buildpackages.lookup_configs(ctx, {1: [1, 2, 3]}) == []
    assert buildpackages.lookup_configs(ctx, [[1, 2, 3]]) == []
    assert buildpackages.lookup_configs(ctx, None) == []

    #
    # the overrides applies to install and to install.upgrade
    # that have no tag, branch or sha1
    #
    config = {
        "overrides": {"install": {"ceph": {"sha1": "overridesha1", "tag": "overridetag", "branch": "overridebranch"}}},
        "tasks": [
            {"install": {"sha1": "installsha1"}},
            {"install.upgrade": {"osd.0": {}, "client.0": {"sha1": "client0sha1"}}},
        ],
    }
    ctx.config = config
    expected_configs = [
        {"branch": "overridebranch", "sha1": "overridesha1", "tag": "overridetag"},
        {"project": "ceph", "branch": "overridebranch", "sha1": "overridesha1", "tag": "overridetag"},
        {"project": "ceph", "sha1": "client0sha1"},
    ]

    assert buildpackages.lookup_configs(ctx, config) == expected_configs
Example #2
0
    def test_update_report_to_send(self, fromConfig, fromOptions, getLogger):
        options = Mock()
        options.interval = 0
        options.oneshot = True
        options.print_ = False
        options.log_dir = ""
        options.log_file = ""
        virtwho = VirtWho(self.logger, options, config_dir="/nonexistant")
        report = Mock()
        report.hash.return_value = "hash"
        config = Mock()
        report.config = config
        config.hash.return_value = "config_hash"
        config.name.return_value = "config_name"
        self.assertTrue(virtwho.update_report_to_send(report))
        self.assertTrue(len(virtwho.configs_ready) == 1 and config in virtwho.configs_ready)
        self.assertTrue(virtwho.reports_to_send[config.hash].hash == report.hash)
        # Pretend we sent the report for that config
        virtwho.configs_ready = []
        virtwho.reports[config.hash] = report.hash
        del virtwho.reports_to_send[config.hash]

        # if we receive the same report twice we should not send it
        self.assertFalse(virtwho.update_report_to_send(report))
        self.assertFalse(virtwho.configs_ready)
        self.assertFalse(virtwho.reports_to_send)
Example #3
0
def test_reconnect_on_socket_error(rabbit_config):

    container = Mock(spec=ServiceContainer)
    container.shared_extensions = {}
    container.config = rabbit_config
    container.max_workers = 1
    container.spawn_managed_thread = spawn_thread

    connection_revived = Mock()

    queue_consumer = QueueConsumer().bind(container)
    queue_consumer.setup()

    queue_consumer.on_connection_revived = connection_revived

    handler = MessageHandler()
    queue_consumer.register_provider(handler)
    queue_consumer.start()

    with patch.object(Connection, "drain_events", autospec=True) as drain_events:
        drain_events.side_effect = socket.error("test-error")

        def check_reconnected():
            assert connection_revived.call_count > 1

        assert_stops_raising(check_reconnected)

    queue_consumer.unregister_provider(handler)
    queue_consumer.stop()
Example #4
0
def test_event_dispatcher(empty_config):

    container = Mock(spec=ServiceContainer)
    container.service_name = "srcservice"
    container.config = empty_config

    service = Mock()
    worker_ctx = WorkerContext(container, service, "dispatch")

    event_dispatcher = EventDispatcher()
    event_dispatcher.bind("dispatch", container)

    path = "nameko.messaging.PublishProvider.prepare"
    with patch(path, autospec=True) as prepare:

        # test start method
        event_dispatcher.prepare()
        assert event_dispatcher.exchange.name == "srcservice.events"
        assert prepare.called

    evt = Mock(type="eventtype", data="msg")
    event_dispatcher.inject(worker_ctx)

    producer = Mock()

    with patch.object(event_dispatcher, "get_producer", autospec=True) as get_producer:
        get_producer.return_value = as_context_manager(producer)

        # test dispatch
        service.dispatch(evt)
        headers = event_dispatcher.get_message_headers(worker_ctx)
        producer.publish.assert_called_once_with(
            evt.data, exchange=event_dispatcher.exchange, headers=headers, routing_key=evt.type
        )
Example #5
0
def test_publish_to_exchange(empty_config, maybe_declare, patch_publisher):
    container = Mock(spec=ServiceContainer)
    container.service_name = "srcservice"
    container.config = empty_config

    service = Mock()
    worker_ctx = WorkerContext(container, service, DummyProvider("publish"))

    publisher = Publisher(exchange=foobar_ex).bind(container, "publish")

    producer = Mock()
    connection = Mock()

    get_connection, get_producer = patch_publisher(publisher)

    get_connection.return_value = as_context_manager(connection)
    get_producer.return_value = as_context_manager(producer)

    # test declarations
    publisher.setup()
    maybe_declare.assert_called_once_with(foobar_ex, connection)

    # test publish
    msg = "msg"
    service.publish = publisher.get_dependency(worker_ctx)
    service.publish(msg, publish_kwarg="value")
    headers = {"nameko.call_id_stack": ["srcservice.publish.0"]}
    producer.publish.assert_called_once_with(
        msg, headers=headers, exchange=foobar_ex, retry=True, retry_policy=DEFAULT_RETRY_POLICY, publish_kwarg="value"
    )
Example #6
0
def test_responder_unserializable_exc(mock_publish):

    message = Mock()
    message.properties = {"reply_to": ""}

    container = Mock()
    container.config = {AMQP_URI_CONFIG_KEY: ""}

    responder = Responder(message)

    # unserialisable exception
    worker_exc = Exception(object())
    result, exc_info = responder.send_response(container, True, (Exception, worker_exc, "tb"))

    # responder will return the TypeError from json.dumps
    assert result is None
    assert exc_info == (TypeError, ANY, ANY)
    assert exc_info[1].message == ("{} is not JSON " "serializable".format(worker_exc.args[0]))

    # and publish a dictionary-serialized UnserializableValueError
    # (where the unserialisable value is a dictionary-serialized worker_exc)
    serialized_exc = serialize(worker_exc)
    expected_msg = {
        "result": None,
        "error": {
            "exc_path": "nameko.exceptions.UnserializableValueError",
            "value": "Unserializable value: `{}`".format(serialized_exc),
            "exc_type": "UnserializableValueError",
            "exc_args": (),
        },
    }
    (msg,), _ = mock_publish.call_args
    assert msg == expected_msg
Example #7
0
def test_reconnect_on_socket_error():

    container = Mock()
    container.config = {AMQP_URI_CONFIG_KEY: None}
    container.max_workers = 1
    container.spawn_managed_thread = spawn_thread

    connection_revived = Mock()

    queue_consumer = QueueConsumer()
    queue_consumer.on_connection_revived = connection_revived

    queue_consumer.bind("queue_consumer", container)

    handler = MessageHandler()
    queue_consumer.register_provider(handler)
    queue_consumer.start()

    with patch.object(Connection, "drain_events", autospec=True) as drain_events:
        drain_events.side_effect = socket.error("test-error")

        def check_reconnected():
            assert connection_revived.call_count > 1

        assert_stops_raising(check_reconnected)
Example #8
0
def test_responder_worker_exc(mock_publish):

    message = Mock()
    message.properties = {"reply_to": ""}

    container = Mock()
    container.config = {AMQP_URI_CONFIG_KEY: ""}

    responder = Responder(message)

    # serialisable exception
    worker_exc = Exception("error")
    result, exc_info = responder.send_response(container, None, (Exception, worker_exc, "tb"))
    assert result is None
    assert exc_info == (Exception, worker_exc, "tb")

    expected_msg = {
        "result": None,
        "error": {
            "exc_path": "exceptions.Exception",
            "value": "error",
            "exc_type": "Exception",
            "exc_args": ("error",),
        },
    }
    (msg,), _ = mock_publish.call_args
    assert msg == expected_msg
Example #9
0
def test_publish_to_queue(empty_config, maybe_declare, patch_publisher):
    container = Mock(spec=ServiceContainer)
    container.service_name = "srcservice"
    container.config = empty_config

    ctx_data = {"language": "en"}
    service = Mock()
    worker_ctx = WorkerContext(container, service, DummyProvider("publish"), data=ctx_data)

    publisher = PublishProvider(queue=foobar_queue)
    publisher.bind("publish", container)

    producer = Mock()
    connection = Mock()

    get_connection, get_producer = patch_publisher(publisher)

    get_connection.return_value = as_context_manager(connection)
    get_producer.return_value = as_context_manager(producer)

    # test declarations
    publisher.prepare()
    maybe_declare.assert_called_once_with(foobar_queue, connection)

    # test publish
    msg = "msg"
    headers = {"nameko.language": "en", "nameko.call_id_stack": ["srcservice.publish.0"]}
    publisher.inject(worker_ctx)
    service.publish(msg, publish_kwarg="value")
    producer.publish.assert_called_once_with(
        msg, headers=headers, exchange=foobar_ex, retry=True, retry_policy=DEFAULT_RETRY_POLICY, publish_kwarg="value"
    )
Example #10
0
def test_publish_custom_headers(empty_config, maybe_declare, patch_publisher):

    container = Mock(spec=ServiceContainer)
    container.service_name = "srcservice"
    container.config = empty_config

    ctx_data = {"language": "en", "customheader": "customvalue"}
    service = Mock()
    worker_ctx = CustomWorkerContext(container, service, "method", data=ctx_data)

    publisher = PublishProvider(queue=foobar_queue)
    publisher.bind("publish", container)

    producer = Mock()
    connection = Mock()

    get_connection, get_producer = patch_publisher(publisher)

    get_connection.return_value = as_context_manager(connection)
    get_producer.return_value = as_context_manager(producer)

    # test declarations
    publisher.prepare()
    maybe_declare.assert_called_once_with(foobar_queue, connection)

    # test publish
    msg = "msg"
    headers = {
        "nameko.language": "en",
        "nameko.customheader": "customvalue",
        "nameko.call_id_stack": ["srcservice.method.0"],
    }
    publisher.inject(worker_ctx)
    service.publish(msg)
    producer.publish.assert_called_once_with(msg, headers=headers, exchange=foobar_ex)
Example #11
0
def test_event_dispatcher(empty_config):

    container = Mock(spec=ServiceContainer)
    container.service_name = "srcservice"
    container.config = empty_config

    service = Mock()
    worker_ctx = WorkerContext(container, service, DummyProvider("dispatch"))

    event_dispatcher = EventDispatcher(retry_policy={"max_retries": 5}).bind(container, attr_name="dispatch")
    event_dispatcher.setup()

    service.dispatch = event_dispatcher.get_dependency(worker_ctx)

    from mock import ANY

    with patch("nameko.standalone.events.producers") as mock_producers:
        with mock_producers[ANY].acquire() as mock_producer:

            service.dispatch("eventtype", "msg")
            headers = event_dispatcher.get_message_headers(worker_ctx)
    mock_producer.publish.assert_called_once_with(
        "msg", exchange=ANY, headers=headers, routing_key="eventtype", retry=True, retry_policy={"max_retries": 5}
    )
    _, call_kwargs = mock_producer.publish.call_args
    exchange = call_kwargs["exchange"]
    assert exchange.name == "srcservice.events"
Example #12
0
def test_dispatch_to_rabbit(rabbit_manager, rabbit_config):

    vhost = rabbit_config["vhost"]

    container = Mock(spec=ServiceContainer)
    container.shared_extensions = {}
    container.service_name = "srcservice"
    container.config = rabbit_config

    service = Mock()
    worker_ctx = WorkerContext(container, service, DummyProvider())

    dispatcher = EventDispatcher().bind(container, "dispatch")
    dispatcher.setup()
    dispatcher.start()

    # we should have an exchange but no queues
    exchanges = rabbit_manager.get_exchanges(vhost)
    queues = rabbit_manager.get_queues(vhost)
    assert "srcservice.events" in [exchange["name"] for exchange in exchanges]
    assert queues == []

    # manually add a queue to capture the events
    rabbit_manager.create_queue(vhost, "event-sink", auto_delete=True)
    rabbit_manager.create_queue_binding(vhost, "srcservice.events", "event-sink", routing_key="eventtype")

    service.dispatch = dispatcher.get_dependency(worker_ctx)
    service.dispatch("eventtype", "msg")

    # test event receieved on manually added queue
    messages = rabbit_manager.get_messages(vhost, "event-sink")
    assert ["msg"] == [msg["payload"] for msg in messages]
def test_nova_rpc_provider(empty_config):

    rpc_consumer = Mock()
    message = Mock(headers={})

    message_body = {"method": "method", "args": {"arg": "arg_value"}, "msg_id": "msg_id", "_context_user_id": "user_id"}

    class Service(object):
        def method(self, arg):
            pass

    container = Mock(spec=ServiceContainer)
    container.shared_extensions = {}
    container.service_cls = Service
    container.worker_ctx_cls = WorkerContext
    container.service_name = "service"
    container.config = empty_config

    entrypoint = NovaRpc().bind(container, "method")
    entrypoint.setup()
    entrypoint.rpc_consumer = rpc_consumer

    container.spawn_worker.side_effect = ContainerBeingKilled()
    entrypoint.handle_message(message_body, message)
    assert rpc_consumer.requeue_message.called
Example #14
0
def test_publish_to_exchange(empty_config, maybe_declare, patch_publisher):
    container = Mock(spec=ServiceContainer)
    container.service_name = "srcservice"
    container.config = empty_config

    service = Mock()
    worker_ctx = WorkerContext(container, service, "publish")

    publisher = PublishProvider(exchange=foobar_ex)
    publisher.bind("publish", container)

    producer = Mock()
    connection = Mock()

    get_connection, get_producer = patch_publisher(publisher)

    get_connection.return_value = as_context_manager(connection)
    get_producer.return_value = as_context_manager(producer)

    # test declarations
    publisher.prepare()
    maybe_declare.assert_called_once_with(foobar_ex, connection)

    # test publish
    msg = "msg"
    publisher.inject(worker_ctx)
    service.publish(msg)
    headers = {"nameko.call_id_stack": ["srcservice.publish.0"]}
    producer.publish.assert_called_once_with(msg, headers=headers, exchange=foobar_ex)
Example #15
0
def test_kill_closes_connections(rabbit_manager, rabbit_config):

    container = Mock(spec=ServiceContainer)
    container.shared_extensions = {}
    container.config = rabbit_config
    container.max_workers = 1
    container.spawn_managed_thread = spawn_thread

    queue_consumer = QueueConsumer().bind(container)
    queue_consumer.setup()

    class Handler(object):
        queue = ham_queue

        def handle_message(self, body, message):
            pass

    queue_consumer.register_provider(Handler())
    queue_consumer.start()

    # kill should close all connections
    queue_consumer.kill()

    # no connections should remain for our vhost
    vhost = rabbit_config["vhost"]
    connections = get_rabbit_connections(vhost, rabbit_manager)
    if connections:
        for connection in connections:
            assert connection["vhost"] != vhost
    def test_get_vm_uuid_not_vm(self):
        vm = Mock()
        vm.config = Mock()
        vm.config.uuid = "this is the uuid"
        self.pv_service.find_vm_by_name = Mock(return_value=vm)

        self.assertRaises(ValueError, self.vm_loader.load_vm_uuid_by_name, self.si, self.vc_model, "path")
Example #17
0
def test_dispatch_to_rabbit(rabbit_manager, rabbit_config):

    vhost = rabbit_config["vhost"]

    container = Mock(spec=ServiceContainer)
    container.service_name = "srcservice"
    container.config = rabbit_config

    service = Mock()
    worker_ctx = WorkerContext(container, service, None)

    dispatcher = EventDispatcher()
    dispatcher.bind("dispatch", container)
    dispatcher.prepare()
    dispatcher.start()

    # we should have an exchange but no queues
    exchanges = rabbit_manager.get_exchanges(vhost)
    queues = rabbit_manager.get_queues(vhost)
    assert "srcservice.events" in [exchange["name"] for exchange in exchanges]
    assert queues == []

    # manually add a queue to capture the events
    rabbit_manager.create_queue(vhost, "event-sink", auto_delete=True)
    rabbit_manager.create_binding(vhost, "srcservice.events", "event-sink", rt_key=ExampleEvent.type)

    dispatcher.inject(worker_ctx)
    service.dispatch(ExampleEvent("msg"))

    # test event receieved on manually added queue
    messages = rabbit_manager.get_messages(vhost, "event-sink")
    assert ["msg"] == [msg["payload"] for msg in messages]
    def test_vm_get_network_by_name_1(self):
        # Arrange
        pv_service = pyVmomiService(None, None, Mock())
        pv_service.wait_for_task = Mock()

        network = Mock()
        network.name = "main_network"

        backing = Mock()
        backing.network = network

        virtual_card = create_autospec(vim.vm.device.VirtualEthernetCard)
        virtual_card.macAddress = "AA-BB"
        virtual_card.backing = backing

        hardware = Mock()
        hardware.device = [virtual_card]

        config = Mock()
        config.hardware = hardware

        vm = Mock()
        vm.config = config

        # Act
        actual_network = pv_service.get_network_by_mac_address(vm, "BB-CC")

        # Assert
        self.assertIsNone(actual_network)
Example #19
0
def test_unserialisable_headers(rabbit_manager, rabbit_config):

    vhost = rabbit_config["vhost"]

    container = Mock(spec=ServiceContainer)
    container.service_name = "service"
    container.config = rabbit_config
    container.spawn_managed_thread = eventlet.spawn

    ctx_data = {"language": "en", "customheader": None}
    service = Mock()
    worker_ctx = CustomWorkerContext(container, service, DummyProvider("method"), data=ctx_data)

    publisher = PublishProvider(exchange=foobar_ex, queue=foobar_queue)
    publisher.bind("publish", container)

    publisher.prepare()
    publisher.start()

    publisher.inject(worker_ctx)
    service.publish("msg")
    messages = rabbit_manager.get_messages(vhost, foobar_queue.name)

    assert messages[0]["properties"]["headers"] == {
        "nameko.language": "en",
        "nameko.call_id_stack": ["service.method.0"],
        # no `customheader`
    }
Example #20
0
def fake_app_patch(test_case):
    project = create_project("myproject")
    app_config = create_app_config(project, "my_app")
    app = Mock()
    app.__version__ = "0"
    app.config = app_config
    app.url = "/-app-/"
    return patch.object(c, "app", app, create=True)
Example #21
0
def test_consume_provider(empty_config):

    container = Mock(spec=ServiceContainer)
    container.worker_ctx_cls = WorkerContext
    container.service_name = "service"
    container.config = empty_config

    worker_ctx = WorkerContext(container, None, DummyProvider())

    spawn_worker = container.spawn_worker
    spawn_worker.return_value = worker_ctx

    queue_consumer = Mock()

    consume_provider = ConsumeProvider(queue=foobar_queue, requeue_on_error=False)
    consume_provider.queue_consumer = queue_consumer
    consume_provider.bind("name", container)

    message = Mock(headers={})

    # test lifecycle
    consume_provider.prepare()
    queue_consumer.register_provider.assert_called_once_with(consume_provider)

    consume_provider.stop()
    queue_consumer.unregister_provider.assert_called_once_with(consume_provider)

    # test handling successful call
    queue_consumer.reset_mock()
    consume_provider.handle_message("body", message)
    handle_result = spawn_worker.call_args[1]["handle_result"]
    handle_result(worker_ctx, "result")
    queue_consumer.ack_message.assert_called_once_with(message)

    # test handling failed call without requeue
    queue_consumer.reset_mock()
    consume_provider.requeue_on_error = False
    consume_provider.handle_message("body", message)
    handle_result = spawn_worker.call_args[1]["handle_result"]
    handle_result(worker_ctx, None, (Exception, Exception("Error"), "tb"))
    queue_consumer.ack_message.assert_called_once_with(message)

    # test handling failed call with requeue
    queue_consumer.reset_mock()
    consume_provider.requeue_on_error = True
    consume_provider.handle_message("body", message)
    handle_result = spawn_worker.call_args[1]["handle_result"]
    handle_result(worker_ctx, None, (Exception, Exception("Error"), "tb"))
    assert not queue_consumer.ack_message.called
    queue_consumer.requeue_message.assert_called_once_with(message)

    # test requeueing on ContainerBeingKilled (even without requeue_on_error)
    queue_consumer.reset_mock()
    consume_provider.requeue_on_error = False
    spawn_worker.side_effect = ContainerBeingKilled()
    consume_provider.handle_message("body", message)
    assert not queue_consumer.ack_message.called
    queue_consumer.requeue_message.assert_called_once_with(message)
Example #22
0
    def test_invalid_scheme(self):
        """
        Test with an invalid scheme in the URL.
        """
        url = "ftpx://martin.com/test"
        importer = Mock()
        importer.config = {}

        self.assertRaises(ValueError, Importer.get_downloader_for_db_importer, importer, url, "/working/dir")
Example #23
0
def _app():
    # Fake app obj
    app = Mock("app")
    config = Mock("config")
    config.releases_release_uri = "foo_%s"
    config.releases_issue_uri = "bar_%s"
    config.releases_debug = False
    app.config = config
    return app
Example #24
0
def test_provider_interval_as_config_fallback():
    container = Mock(spec=ServiceContainer)
    container.service_name = "service"
    container.config = {}

    timer = TimerProvider(interval=1, config_key="spam-conf")
    timer.bind("foobar", container)
    timer.prepare()

    assert timer.interval == 1
Example #25
0
def mock_container(request, empty_config):
    from mock import Mock
    from nameko.constants import SERIALIZER_CONFIG_KEY, DEFAULT_SERIALIZER
    from nameko.containers import ServiceContainer

    container = Mock(spec=ServiceContainer)
    container.config = empty_config
    container.config[SERIALIZER_CONFIG_KEY] = DEFAULT_SERIALIZER
    container.serializer = container.config[SERIALIZER_CONFIG_KEY]
    container.accept = [DEFAULT_SERIALIZER]
    return container
 def test_handle_lifecycle_control(self):
     ctrl = Mock()
     ctrl.message = "start"
     ctrl.config = ConfigParser()
     self.assertRaises(RuntimeError, self.participant.handle_lifecycle_control, ctrl)
     ctrl.config.add_section("obs")
     ctrl.config.set("obs", "oscrc", "oscrc_file")
     self.participant.handle_lifecycle_control(ctrl)
     ctrl.config.add_section("check_yaml")
     ctrl.config.set("check_yaml", "spec_pattern", "test")
     self.participant.handle_lifecycle_control(ctrl)
Example #27
0
def test_consume_from_rabbit(rabbit_manager, rabbit_config):

    vhost = rabbit_config["vhost"]

    container = Mock(spec=ServiceContainer)
    container.worker_ctx_cls = CustomWorkerContext
    container.service_name = "service"
    container.config = rabbit_config
    container.max_workers = 10

    def spawn_thread(method, protected):
        return eventlet.spawn(method)

    container.spawn_managed_thread = spawn_thread

    worker_ctx = CustomWorkerContext(container, None, DummyProvider())

    factory = DependencyFactory(ConsumeProvider, queue=foobar_queue, requeue_on_error=False)
    consumer = factory.create_and_bind_instance("injection_name", container)

    # prepare and start dependencies
    consumer.prepare()
    consumer.queue_consumer.prepare()
    consumer.start()
    consumer.queue_consumer.start()

    # test queue, exchange and binding created in rabbit
    exchanges = rabbit_manager.get_exchanges(vhost)
    queues = rabbit_manager.get_queues(vhost)
    bindings = rabbit_manager.get_queue_bindings(vhost, foobar_queue.name)

    assert "foobar_ex" in [exchange["name"] for exchange in exchanges]
    assert "foobar_queue" in [queue["name"] for queue in queues]
    assert "foobar_ex" in [binding["source"] for binding in bindings]

    # test message consumed from queue
    container.spawn_worker.return_value = worker_ctx

    headers = {"nameko.language": "en", "nameko.customheader": "customvalue"}
    rabbit_manager.publish(vhost, foobar_ex.name, "", "msg", properties=dict(headers=headers))

    ctx_data = {"language": "en", "customheader": "customvalue"}
    with wait_for_call(CONSUME_TIMEOUT, container.spawn_worker) as method:
        method.assert_called_once_with(consumer, ("msg",), {}, context_data=ctx_data, handle_result=ANY_PARTIAL)
        handle_result = method.call_args[1]["handle_result"]

    # ack message
    handle_result(worker_ctx, "result")

    # stop will hang if the consumer hasn't acked or requeued messages
    with eventlet.timeout.Timeout(CONSUME_TIMEOUT):
        consumer.stop()

    consumer.queue_consumer.kill()
Example #28
0
def test_provider_uses_config_for_interval():
    container = Mock(spec=ServiceContainer)
    container.service_name = "service"
    container.config = {"spam-conf": 10}
    container.spawn_managed_thread = eventlet.spawn

    timer = TimerProvider(interval=None, config_key="spam-conf")
    timer.bind("foobar", container)
    timer.prepare()

    assert timer.interval == 10
 def setUp(self):  # pylint: disable=C0103
     """Test setup."""
     os.mkdir(TMP)
     self.queuename = os.path.join(TMP, "wq")
     ctrl = Mock()
     ctrl.message = "start"
     ctrl.config = ConfigParser()
     ctrl.config.add_section("obsticket")
     ctrl.config.set("obsticket", "prjdir", TMP)
     self.participant = obsticket.ParticipantHandler()
     self.participant.handle_lifecycle_control(ctrl)
    def test_send_message_for_Event(self, get_topic):
        topic = get_topic.return_value
        manager = Mock()
        manager.config = {"tasks": {}}
        task = Mock(wraps=Task(manager, "fake"))
        task.options.test = False
        event = Mock()
        task.accepted = [event]

        e = notify_sns.SNSNotificationEmitter({"aws_region": "test", "sns_topic_arn": "arn"})
        e.send_notifications(task)
        topic.publish.assert_called_once_with(Message=event.render.return_value)