Here are the examples of the python api pytest_twisted.inlineCallbacks taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

145 Examples 7

			 
			     @pytest_twisted.inlineCallbacks
def test_twisted_consume_serverside_cancel(queue_and_binding):
    """
    Assert the consumer halts and ``consumer.result`` errbacks when the server
    explicitly cancels the consumer (by deleting the queue).
    """
    queues, bindings = queue_and_binding

    consumers = yield api.twisted_consume(lambda x: x, bindings, queues)

    # Delete the queue and assert the consumer errbacks
    url = "{base}queues/%2F/{queue}".format(base=HTTP_API, queue=list(queues.keys())[0])
    yield treq.delete(url, auth=HTTP_AUTH, timeout=3)

    _add_timeout(consumers[0].result, 10)
    try:
        yield consumers[0].result
        pytest.fail("Consumer did not errback!")
    except exceptions.ConsumerCanceled:
        pass
    except (defer.TimeoutError, defer.CancelledError):
        pytest.fail("Timeout reached without consumer calling its errback!")
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_twisted_consume_general_exception(queue_and_binding):
    """
    Assert if the callback raises an unhandled exception, it is passed on to the
    consumer.result and the message is re-queued.
    """
    queues, bindings = queue_and_binding
    msg = message.Message(
        topic=u"nice.message",
        headers={u"niceness": u"very"},
        body={u"encouragement": u"You're doing great!"},
    )

    def callback(message):
        """An *exceptionally* useless callback"""
        raise Exception("Oh the huge manatee")

    # Assert that the number of consumers we think we started is the number the
    # server things we started. This will fail if other tests don't clean up properly.
    # If it becomes problematic perhaps each test should have a vhost.
    consumers = yield api.twisted_consume(callback, bindings, queues)
    yield threads.deferToThread(api.publish, msg, "amq.topic")

    _add_timeout(consumers[0].result, 10)
    try:
        yield consumers[0].result
        pytest.fail("Expected an exception to be raised.")
    except (defer.TimeoutError, defer.CancelledError):
        pytest.fail("Timeout reached without consumer halting!")
    except Exception as e:
        # Assert the message was delivered and re-queued when the consumer crashed.
        assert e.args[0] == "Oh the huge manatee"
        server_queue = yield get_queue(queues)
        assert server_queue["consumers"] == 0
        assert server_queue["messages"] == 1
    finally:
        yield consumers[0].cancel()
				 
			
			 
			     @pytest.mark.parametrize(
    "callback,exit_code,msg",
    [
        ("halt_exit_0", 0, b"Consumer indicated it wishes consumption to halt"),
        ("halt_exit_42", 42, b"Life, the universe, and everything"),
    ],
)
@pytest_twisted.inlineCallbacks
def test_consume_halt_with_exitcode(callback, exit_code, msg, queue):
    """Assert user execution halt with reason and exit_code is reported."""
    args = [
        "fedora-messaging",
        "--conf={}".format(CLI_CONF),
        "consume",
        "--callback=fedora_messaging.tests.integration.test_cli:{}".format(callback),
        "--queue-name={}".format(queue),
        "--exchange=amq.topic",
        "--routing-key=#",
    ]

    process = subprocess.Popen(args, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    time.sleep(5)

    yield threads.deferToThread(api.publish, message.Message())
    for _ in range(5):
        time.sleep(1)
        if process.poll() is not None:
            break
    else:
        process.kill()
        pytest.fail("Process never stopped!: {}".format(process.stdout.read()))

    assert process.returncode == exit_code
    assert msg in process.stdout.read()
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def get_queue(queue_dict, delay=10):
    """
    Retrieve data about a queue in the broker in the default vhost ("/").

    Args:
        delay: Time to wait before querying the server. It can take some time for
            everything to settle and become available in the HTTP API. 10 seconds
            was arrived at after intermittent failures at lower values.

    Returns:
        dict: A dictionary representation of the queue.
    """
    queues = list(queue_dict.keys())
    name = queues[0]
    # Assert both messages are delivered, no messages are un-acked, and only one
    # message got a positive acknowledgment.
    url = "{base}queues/%2F/{queue}".format(base=HTTP_API, queue=name)
    server_queue = yield task.deferLater(
        reactor, delay, treq.get, url, auth=HTTP_AUTH, timeout=3
    )
    server_queue = yield server_queue.json()
    defer.returnValue(server_queue)
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_no_read_permissions_bind_failure(admin_user, queue_and_binding):
    """Assert the call to twisted_consume errbacks on read permissions errors on binding."""
    queues, bindings = queue_and_binding
    url = "{base}permissions/%2F/{user}".format(base=HTTP_API, user=admin_user)
    body = {"configure": ".*", "write": ".*", "read": ""}
    resp = yield treq.put(url, json=body, auth=HTTP_AUTH, timeout=3)
    assert resp.code == 204

    amqp_url = "amqp://{user}:[email protected]:5672/%2F".format(user=admin_user)
    try:
        with mock.patch.dict(config.conf, {"amqp_url": amqp_url}):
            yield api.twisted_consume(lambda x: x, bindings, queues)
        pytest.fail("Call failed to raise an exception")
    except exceptions.BadDeclaration as e:
        assert e.reason.args[0] == 403
        assert e.reason.args[1] == (
            "ACCESS_REFUSED - access to exchange 'amq.topic' in vhost '/' refused for user"
            " '{}'".format(admin_user)
        )
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_unhandled_exception_cancels_consumer():
    """Assert any unhandled Exception results in the consumer being canceled."""
    queue = str(uuid.uuid4())
    queues = [
        {
            "queue": queue,
            "auto_delete": True,
            "durable": False,
            "exclusive": False,
            "arguments": {"x-expires": 60 * 1000},
        }
    ]
    serv = service.FedoraMessagingService(amqp_url="amqp://")

    serv.startService()
    client = yield serv.getFactory().whenConnected()
    yield client.declare_queues(queues)
    yield client.bind_queues(
        [{"queue": queue, "exchange": "amq.topic", "routing_key": "#"}]
    )

    def callback(message):
        raise Exception("Panic!")

    yield client.consume(callback, queue)
    assert len(client._consumers) == 1

    yield client.publish(message.Message(), "amq.topic")
    yield task.deferLater(reactor, 3.0, lambda: True)
    assert len(client._consumers) == 0
    yield serv.stopService()
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_twisted_stop_service(queue_and_binding):
    """
    Assert stopping the service, which happens when the reactor shuts down, waits
    for consumers to finish processing and then cancels them before closing the connection.
    """
    queues, bindings = queue_and_binding
    message_received, message_processed = defer.Deferred(), defer.Deferred()

    def callback(message):
        """Callback when the message is received, introduce a delay, then callback again."""
        reactor.callFromThread(message_received.callback, None)
        time.sleep(5)
        reactor.callFromThread(message_processed.callback, None)

    consumers = yield api.twisted_consume(callback, bindings, queues)
    yield threads.deferToThread(api.publish, message.Message(), "amq.topic")

    _add_timeout(consumers[0].result, 10)
    _add_timeout(message_received, 10)
    try:
        yield message_received
    except (defer.TimeoutError, defer.CancelledError):
        yield consumers[0].cancel()
        pytest.fail("Timeout reached without consumer receiving message!")

    assert not message_processed.called
    deferred_stop = api._twisted_service.stopService()

    _add_timeout(message_processed, 10)
    try:
        yield message_processed
        # The request to stop should wait on the message to be processed
        assert deferred_stop.called is False
    except (defer.TimeoutError, defer.CancelledError):
        pytest.fail("Timeout reached without consumer processing message")
    yield deferred_stop
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_no_vhost_permissions(admin_user, queue_and_binding):
    """Assert a hint is given if the user doesn't have any access to the vhost"""
    url = "{base}permissions/%2F/{user}".format(base=HTTP_API, user=admin_user)
    resp = yield treq.delete(url, auth=HTTP_AUTH, timeout=3)
    assert resp.code == 204

    queues, _ = queue_and_binding

    amqp_url = "amqp://{user}:[email protected]:5672/%2F".format(user=admin_user)
    with mock.patch.dict(config.conf, {"amqp_url": amqp_url}):
        try:
            yield api.twisted_consume(lambda x: x, [], queues)
        except exceptions.ConnectionException as e:
            assert e.reason == (
                "The TCP connection appears to have started, but the TLS or AMQP "
                "handshake with the broker failed; check your connection and "
                "authentication parameters and ensure your user has permission "
                "to access the vhost"
            )
				 
			
			 
			     @pytest.fixture
def admin_user():
    """
    Fixture that creates a random admin user and deletes the user afterwards.

    Useful if the test wishes to alter permissions to test failure cases. Default
    permissions is complete access to the "/" vhost.

    Returns:
        The username of the new administrator. The password is "guest".
    """
    # Create a user with no permissions
    username = str(uuid.uuid4())
    url = "{base}users/{user}".format(base=HTTP_API, user=username)
    body = {"username": username, "password": "guest", "tags": "administrator"}
    deferred_resp = treq.put(url, json=body, auth=HTTP_AUTH, timeout=3)

    @pytest_twisted.inlineCallbacks
    def cp(resp):
        assert resp.code == 201
        url = "{base}permissions/%2F/{user}".format(base=HTTP_API, user=username)
        body = {"configure": ".*", "write": ".*", "read": ".*"}
        resp = yield treq.put(url, json=body, auth=HTTP_AUTH, timeout=3)
        assert resp.code == 201

    deferred_resp.addCallbacks(cp, cp)
    pytest_twisted.blockon(deferred_resp)
    yield username

    # Cleanup
    deferred_resp = treq.delete(url, auth=HTTP_AUTH, timeout=3)
    pytest_twisted.blockon(deferred_resp)
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_twisted_consume_drop_message(queue_and_binding):
    """Assert raising Drop causes the message to be dropped, but processing continues."""
    queues, bindings = queue_and_binding
    msg = message.Message(
        topic=u"nice.message",
        headers={u"niceness": u"very"},
        body={u"encouragement": u"You're doing great!"},
    )
    dropped_messages = []

    def callback(message):
        """Drop 1 message and then halt on the second message."""
        dropped_messages.append(message)
        if len(dropped_messages) == 2:
            raise exceptions.HaltConsumer()
        raise exceptions.Drop()

    # Assert that the number of consumers we think we started is the number the
    # server things we started. This will fail if other tests don't clean up properly.
    # If it becomes problematic perhaps each test should have a vhost.
    consumers = yield api.twisted_consume(callback, bindings, queues)
    yield threads.deferToThread(api.publish, msg, "amq.topic")
    yield threads.deferToThread(api.publish, msg, "amq.topic")

    _add_timeout(consumers[0].result, 10)
    try:
        yield consumers[0].result
    except exceptions.HaltConsumer:
        # Assert both messages are delivered, no messages are un-acked, and only one
        # message got a positive acknowledgment.
        server_queue = yield get_queue(queues)
        assert server_queue["consumers"] == 0
        assert server_queue["messages"] == 0
    except (defer.TimeoutError, defer.CancelledError):
        pytest.fail("Timeout reached without consumer halting!")
    finally:
        yield consumers[0].cancel()
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_publish_channel_error(queue_and_binding):
    """Assert publishing recovers from a channel error."""
    queues, bindings = queue_and_binding

    def counting_callback(message, storage=defaultdict(int)):
        storage[message.topic] += 1
        if storage[message.topic] == 2:
            raise exceptions.HaltConsumer()

    @pytest_twisted.inlineCallbacks
    def delayed_publish():
        """Publish, break the channel, and publish again."""
        yield threads.deferToThread(api.publish, message.Message(), "amq.topic")
        protocol = yield api._twisted_service._service.factory.when_connected()
        yield protocol._publish_channel.close()
        yield threads.deferToThread(api.publish, message.Message(), "amq.topic")

    reactor.callLater(5, delayed_publish)

    deferred_consume = threads.deferToThread(
        api.consume, counting_callback, bindings, queues
    )
    deferred_consume.addTimeout(30, reactor)
    try:
        yield deferred_consume
        pytest.fail("consume should have raised an exception")
    except (defer.TimeoutError, defer.CancelledError):
        pytest.fail("Consumer did not receive both messages")
    except exceptions.HaltConsumer as e:
        assert 0 == e.exit_code
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_twisted_consume_update_callback(queue_and_binding):
    """Assert a second call to consume updates an existing callback."""
    queues, bindings = queue_and_binding

    callback1 = defer.Deferred()
    callback2 = defer.Deferred()

    consumers1 = yield api.twisted_consume(
        lambda m: reactor.callFromThread(callback1.callback, m), bindings, queues
    )
    yield threads.deferToThread(api.publish, message.Message(), "amq.topic")
    _add_timeout(callback1, 10)
    try:
        yield callback1
    except (defer.TimeoutError, defer.CancelledError):
        pytest.fail("Never received message for initial callback")

    consumers2 = yield api.twisted_consume(
        lambda m: reactor.callFromThread(callback2.callback, m), bindings, queues
    )
    yield threads.deferToThread(api.publish, message.Message(), "amq.topic")
    _add_timeout(callback2, 10)
    try:
        yield callback2
    except (defer.TimeoutError, defer.CancelledError):
        pytest.fail("Never received message for updated callback")

    assert consumers1[0]._tag == consumers2[0]._tag

    yield consumers2[0].cancel()
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_twisted_consume_invalid_message(queue_and_binding):
    """Assert messages that fail validation are nacked."""
    queues, bindings = queue_and_binding
    bindings[0]["routing_keys"] = ["test_twisted_invalid_message"]

    consumers = yield api.twisted_consume(
        lambda x: pytest.fail("Message should be nacked"), bindings, queues
    )

    url = HTTP_API + "exchanges/%2F/amq.topic/publish"
    body = {
        "properties": {},
        "routing_key": "test_twisted_invalid_message",
        "payload": "not json",
        "payload_encoding": "string",
    }
    response = yield treq.post(url, json=body, auth=HTTP_AUTH, timeout=3)
    response = yield response.json()
    assert response["routed"] is True
    yield consumers[0].cancel()
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_twisted_consume_cancel(queue_and_binding):
    """Assert canceling works with :func:`fedora_messaging.api.twisted_consume` API."""
    queues, bindings = queue_and_binding

    # Assert that the number of consumers we think we started is the number the
    # server things we started. This will fail if other tests don't clean up properly.
    # If it becomes problematic perhaps each test should have a vhost.
    consumers = yield api.twisted_consume(lambda m: m, bindings, queues)
    consumers[0].result.addErrback(pytest.fail)

    server_queue = yield get_queue(queues)
    assert server_queue["consumers"] == 1

    try:
        d = consumers[0].cancel()
        _add_timeout(d, 5)
        yield d

        # Assert the consumer.result deferred has called back when the cancel
        # deferred fires.
        assert consumers[0].result.called

        # Finally make sure the server agrees that the consumer is canceled.
        server_queue = yield get_queue(queues)
        assert server_queue["consumers"] == 0
    except (defer.TimeoutError, defer.CancelledError):
        pytest.fail("Timeout reached without consumer halting!")
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_nack_handled():
    """Assert raising Nack in a consumer works and messages are re-delivered"""
    queue = str(uuid.uuid4())
    queues = [
        {
            "queue": queue,
            "auto_delete": True,
            "durable": False,
            "exclusive": False,
            "arguments": {"x-expires": 60 * 1000},
        }
    ]
    messages = []
    serv = service.FedoraMessagingService(amqp_url="amqp://")

    serv.startService()
    client = yield serv.getFactory().whenConnected()
    yield client.declare_queues(queues)
    yield client.bind_queues(
        [{"queue": queue, "exchange": "amq.topic", "routing_key": "#"}]
    )

    def callback(message):
        messages.append(message)
        if len(messages) < 3:
            raise exceptions.Nack()

    yield client.consume(callback, queue)
    assert len(client._consumers) == 1

    yield client.publish(message.Message(), "amq.topic")
    yield task.deferLater(reactor, 3.0, lambda: True)

    assert len(messages) == 3
    assert len(set([m.id for m in messages])) == 1
    assert len(client._consumers) == 1

    yield client.cancel(queue)
    serv.stopService()
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_drop_handled():
    """Assert raising Drop in a consumer works and messages are not re-delivered"""
    queue = str(uuid.uuid4())
    messages = []
    serv = service.FedoraMessagingService(amqp_url="amqp://")
    serv.startService()
    client = yield serv.getFactory().whenConnected()
    queues = [
        {
            "queue": queue,
            "auto_delete": True,
            "durable": False,
            "exclusive": False,
            "arguments": {"x-expires": 60 * 1000},
        }
    ]
    yield client.declare_queues(queues)
    yield client.bind_queues(
        [{"queue": queue, "exchange": "amq.topic", "routing_key": "#"}]
    )

    def callback(message):
        messages.append(message)
        raise exceptions.Drop()

    yield client.consume(callback, queue)
    assert len(client._consumers) == 1

    yield client.publish(message.Message(), "amq.topic")
    yield task.deferLater(reactor, 3.0, lambda: True)  # Just wait a few seconds

    assert len(messages) == 1
    assert len(client._consumers) == 1
    yield client.cancel(queue)
    yield serv.stopService()
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_no_read_permissions_queue_read_failure_pika1(admin_user, queue_and_binding):
    """
    Assert an errback occurs when unable to read from the queue due to
    permissions. This is a bit weird because the consumer has permission to
    register itself, but not to actually read from the queue so the result is
    what errors back.
    """
    queues, bindings = queue_and_binding
    url = "{base}permissions/%2F/{user}".format(base=HTTP_API, user=admin_user)
    body = {"configure": ".*", "write": ".*", "read": ""}
    resp = yield treq.put(url, json=body, auth=HTTP_AUTH, timeout=3)
    assert resp.code == 204

    amqp_url = "amqp://{user}:[email protected]:5672/%2F".format(user=admin_user)
    with mock.patch.dict(config.conf, {"amqp_url": amqp_url}):
        try:
            consumers = api.twisted_consume(lambda x: x, [], queues)
            _add_timeout(consumers, 5)
            yield consumers
            pytest.fail("Call failed to raise an exception")
        except exceptions.PermissionException as e:
            assert e.reason == (
                "ACCESS_REFUSED - access to queue '{}' in vhost '/' refused for user "
                "'{}'".format(list(queues.keys())[0], admin_user)
            )
        except (defer.TimeoutError, defer.CancelledError):
            pytest.fail("Timeout reached without consumer calling its errback!")
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_no_write_permissions(admin_user, queue_and_binding):
    """Assert the call to twisted_consume errbacks on write permissions errors."""
    queues, bindings = queue_and_binding
    url = "{base}permissions/%2F/{user}".format(base=HTTP_API, user=admin_user)
    body = {"configure": ".*", "write": "", "read": ".*"}
    resp = yield treq.put(url, json=body, auth=HTTP_AUTH, timeout=3)
    assert resp.code == 204

    amqp_url = "amqp://{user}:[email protected]:5672/%2F".format(user=admin_user)
    try:
        with mock.patch.dict(config.conf, {"amqp_url": amqp_url}):
            yield api.twisted_consume(lambda x: x, bindings, queues)
        pytest.fail("Call failed to raise an exception")
    except exceptions.BadDeclaration as e:
        assert e.reason.args[0] == 403
        assert e.reason.args[1] == (
            "ACCESS_REFUSED - access to queue '{}' in vhost '/' refused for user"
            " '{}'".format(list(queues.keys())[0], admin_user)
        )
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_twisted_consume_nack_message(queue_and_binding):
    """Assert raising Nack causes the message to be replaced in the queue."""
    queues, bindings = queue_and_binding
    msg = message.Message(
        topic=u"nice.message",
        headers={u"niceness": u"very"},
        body={u"encouragement": u"You're doing great!"},
    )
    nacked_messages = []

    def callback(message):
        """Nack the message, then halt."""
        nacked_messages.append(message)
        if len(nacked_messages) == 2:
            raise exceptions.HaltConsumer()
        raise exceptions.Nack()

    # Assert that the number of consumers we think we started is the number the
    # server things we started. This will fail if other tests don't clean up properly.
    # If it becomes problematic perhaps each test should have a vhost.
    consumers = yield api.twisted_consume(callback, bindings, queues)
    yield threads.deferToThread(api.publish, msg, "amq.topic")

    _add_timeout(consumers[0].result, 10)
    try:
        yield consumers[0].result
    except exceptions.HaltConsumer:
        # Assert the message was delivered, redelivered when Nacked, then acked by HaltConsumer
        server_queue = yield get_queue(queues)
        assert server_queue["consumers"] == 0
        assert server_queue["messages"] == 0
    except (defer.TimeoutError, defer.CancelledError):
        pytest.fail("Timeout reached without consumer halting!")
    finally:
        yield consumers[0].cancel()
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_pub_sub_default_settings(queue_and_binding):
    """
    Assert publishing and subscribing works with the default configuration.

    This should work because the publisher uses the 'amq.topic' exchange by
    default and the consumer also uses the 'amq.topic' exchange with its
    auto-named queue and a default subscription key of '#'.
    """
    queues, bindings = queue_and_binding

    # Consumer setup
    def counting_callback(message, storage=defaultdict(int)):
        storage[message.topic] += 1
        if storage[message.topic] == 3:
            raise exceptions.HaltConsumer()

    deferred_consume = threads.deferToThread(
        api.consume, counting_callback, bindings, queues
    )

    @pytest_twisted.inlineCallbacks
    def delayed_publish():
        """Give the consumer time to setup."""
        msg = message.Message(
            topic=u"nice.message",
            headers={u"niceness": u"very"},
            body={u"encouragement": u"You're doing great!"},
        )
        for _ in range(0, 3):
            try:
                yield threads.deferToThread(api.publish, msg, "amq.topic")
            except exceptions.ConnectionException:
                pytest.fail("Failed to publish message, is the broker running?")

    reactor.callLater(5, delayed_publish)
    deferred_consume.addTimeout(30, reactor)
    try:
        yield deferred_consume
        pytest.fail("consume should have raised an exception")
    except (defer.TimeoutError, defer.CancelledError):
        pytest.fail("Timeout reached without consumer halting!")
    except exceptions.HaltConsumer as e:
        assert 0 == e.exit_code
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_twisted_consume_halt_consumer(queue_and_binding):
    """
    Assert raising HaltConsumer works with :func:`fedora_messaging.api.twisted_consume`
    API.
    """
    queues, bindings = queue_and_binding
    msg = message.Message(
        topic=u"nice.message",
        headers={u"niceness": u"very"},
        body={u"encouragement": u"You're doing great!"},
    )
    expected_headers = {
        u"fedora_messaging_severity": 20,
        u"fedora_messaging_schema": u"base.message",
        u"niceness": u"very",
    }
    messages_received = []

    def callback(message):
        """Count to 3 and quit."""
        messages_received.append(message)
        if len(messages_received) == 3:
            raise exceptions.HaltConsumer()

    consumers = yield api.twisted_consume(callback, bindings, queues)

    # Assert the server reports a consumer
    server_queue = yield get_queue(queues)
    assert server_queue["consumers"] == 1

    for _ in range(0, 3):
        yield threads.deferToThread(api.publish, msg, "amq.topic")

    _add_timeout(consumers[0].result, 10)
    try:
        yield consumers[0].result
    except exceptions.HaltConsumer as e:
        assert len(messages_received) == 3
        assert e.exit_code == 0
        for m in messages_received:
            assert u"nice.message" == m.topic
            assert {u"encouragement": u"You're doing great!"} == m.body
            assert "sent-at" in m._headers
            del m._headers["sent-at"]
            assert expected_headers == m._headers
        server_queue = yield get_queue(queues)
        assert server_queue["consumers"] == 0
    except (defer.TimeoutError, defer.CancelledError):
        yield consumers[0].cancel()
        pytest.fail("Timeout reached without consumer halting!")
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_basic_pub_sub():
    """Basic test of the Twisted publishing/subscribing support"""
    queue = str(uuid.uuid4())
    queues = [
        {
            "queue": queue,
            "auto_delete": True,
            "durable": False,
            "exclusive": False,
            "arguments": {"x-expires": 60 * 1000},
        }
    ]
    msg = message.Message(
        topic=u"nice.message",
        headers={u"niceness": u"very"},
        body={u"encouragement": u"You're doing great!"},
    )
    expected_headers = {
        u"fedora_messaging_severity": 20,
        u"fedora_messaging_schema": u"base.message",
        u"niceness": u"very",
    }
    messages_received = []
    serv = service.FedoraMessagingService(amqp_url="amqp://")

    serv.startService()
    client = yield serv.getFactory().whenConnected()
    yield client.declare_queues(queues)
    yield client.bind_queues(
        [{"queue": queue, "exchange": "amq.topic", "routing_key": "#"}]
    )

    def callback(message):
        messages_received.append(message)
        if len(messages_received) == 3:
            raise exceptions.HaltConsumer()

    yield client.consume(callback, queue)
    for _ in range(0, 3):
        yield client.publish(msg, "amq.topic")
    yield task.deferLater(reactor, 3.0, lambda: True)
    yield serv.stopService()

    assert len(messages_received) == 3
    for m in messages_received:
        assert u"nice.message" == m.topic
        assert {u"encouragement": u"You're doing great!"} == m.body
        assert "sent-at" in m._headers
        del m._headers["sent-at"]
        assert expected_headers == m._headers
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_twisted_consume_connection_reset(queue_and_binding):
    """
    Assert consuming works across connections and handles connection resets.

    This test sets up a queue, publishes 2 messages to itself, then kills all active
    connections on the broker. It then sends a third message and asserts the consumer
    gets it.
    """
    queues, bindings = queue_and_binding
    msg = message.Message(
        topic=u"nice.message",
        headers={u"niceness": u"very"},
        body={u"encouragement": u"You're doing great!"},
    )
    messages_received = []
    two_received = defer.Deferred()  # Fired by the callback on 2 messages

    def callback(message):
        """Count to, 2, fire a deferred, then count to 3 and quit."""
        messages_received.append(message)
        if len(messages_received) == 2:
            two_received.callback(None)
        if len(messages_received) == 3:
            raise exceptions.HaltConsumer()

    consumers = yield api.twisted_consume(callback, bindings, queues)

    # Wait for two messages to get through, kill the connection, and then send
    # the third and wait for the consumer to finish
    yield threads.deferToThread(api.publish, msg, "amq.topic")
    yield threads.deferToThread(api.publish, msg, "amq.topic")
    _add_timeout(two_received, 10)
    try:
        yield two_received
    except (defer.TimeoutError, defer.CancelledError):
        pytest.fail("Timeout reached without receiving first two messages")

    for _ in range(10):
        conns = yield task.deferLater(
            reactor, 1, treq.get, HTTP_API + "connections", auth=HTTP_AUTH, timeout=3
        )
        conns = yield conns.json()
        this_conn = [
            c
            for c in conns
            if "app" in c["client_properties"]
            and c["client_properties"]["app"] == "test_twisted_consume_connection_reset"
        ]
        if this_conn:
            cname = six.moves.urllib.parse.quote(this_conn[0]["name"])
            yield treq.delete(
                HTTP_API + "connections/" + cname, auth=HTTP_AUTH, timeout=3
            )
            break
    else:
        pytest.fail("Unable to find and kill connection!")

    # The consumer should receive this third message after restarting its connection
    # and then it should exit gracefully.
    yield threads.deferToThread(api.publish, msg, "amq.topic")
    _add_timeout(consumers[0].result, 10)
    try:
        yield consumers[0].result
    except exceptions.HaltConsumer:
        assert len(messages_received) == 3
    except (defer.TimeoutError, defer.CancelledError):
        yield consumers[0].cancel()
        pytest.fail("Timeout reached without consumer halting!")
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_vmware_disconnect():
    collect_only = {
        'vms': True,
        'vmguests': True,
        'datastores': True,
        'hosts': True,
        'snapshots': True,
    }
    collector = VmwareCollector(
        '127.0.0.1',
        'root',
        'password',
        5000,
        collect_only,
    )

    # Mock that we have a connection
    connection = object()
    collector.connection = connection

    with mock.patch('vmware_exporter.vmware_exporter.connect') as connect:
        yield collector._vmware_disconnect()
        connect.Disconnect.assert_called_with(connection)
				 
			
			 
			     @pytest.mark.twisted
@pytest_twisted.inlineCallbacks
def test_apc_pdu(snmp_agent_proxy):
    snmp_agent_proxy.community = 'apc-pdu'
    snmp_agent_proxy.open()
    mib = powernet_mib.PowerNetMib(snmp_agent_proxy)
    res = yield mib.get_all_sensors()
    assert res == [
        {
            'description': 'PDU Phase 1 ampere load',
            'internal_name': 'rPDULoadStatusLoad1',
            'mib': 'PowerNet-MIB',
            'name': 'PDU Phase 1',
            'oid': '.1.3.6.1.4.1.318.1.1.12.2.3.1.1.2.1',
            'precision': 1,
            'scale': None,
            'unit_of_measurement': 'amperes'
        },
        {
            'description': 'PDU Bank 1 ampere load',
            'internal_name': 'rPDULoadStatusLoad2',
            'mib': 'PowerNet-MIB',
            'name': 'PDU Bank 1',
            'oid': '.1.3.6.1.4.1.318.1.1.12.2.3.1.1.2.2',
            'precision': 1,
            'scale': None,
            'unit_of_measurement': 'amperes'
        },
        {
            'description': 'PDU Bank 2 ampere load',
            'internal_name': 'rPDULoadStatusLoad3',
            'mib': 'PowerNet-MIB',
            'name': 'PDU Bank 2',
            'oid': '.1.3.6.1.4.1.318.1.1.12.2.3.1.1.2.3',
            'precision': 1,
            'scale': None,
            'unit_of_measurement': 'amperes'
        },
    ]
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_counter_ids():
    counter = mock.Mock()
    counter.groupInfo.key = 'a'
    counter.nameInfo.key = 'b'
    counter.rollupType = 'c'
    counter.key = 1

    content = mock.Mock()
    content.perfManager.perfCounter = [counter]

    collect_only = {
        'vms': True,
        'vmguests': True,
        'datastores': True,
        'hosts': True,
        'snapshots': True,
    }
    collector = VmwareCollector(
        '127.0.0.1',
        'root',
        'password',
        5000,
        collect_only,
    )
    collector.content = content

    result = yield collector.counter_ids
    assert result == {'a.b.c': 1}
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_vmware_connect():
    collect_only = {
        'vms': True,
        'vmguests': True,
        'datastores': True,
        'hosts': True,
        'snapshots': True,
    }
    collector = VmwareCollector(
        '127.0.0.1',
        'root',
        'password',
        collect_only,
        5000,
        ignore_ssl=True,
    )

    with mock.patch('vmware_exporter.vmware_exporter.connect') as connect:
        yield collector.connection

        call_kwargs = connect.SmartConnect.call_args[1]
        assert call_kwargs['host'] == '127.0.0.1'
        assert call_kwargs['user'] == 'root'
        assert call_kwargs['pwd'] == 'password'
        assert call_kwargs['sslContext'] is not None
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_collect():
    collect_only = {
        'vms': True,
        'vmguests': True,
        'datastores': True,
        'hosts': True,
        'snapshots': True,
    }
    collector = VmwareCollector(
        '127.0.0.1',
        'root',
        'password',
        collect_only,
        5000,
        ignore_ssl=True,
    )
    collector.content = _succeed(mock.Mock())

    with contextlib.ExitStack() as stack:
        stack.enter_context(mock.patch.object(collector, '_vmware_get_vms')).return_value = _succeed(True)
        stack.enter_context(
            mock.patch.object(collector, '_vmware_get_vm_perf_manager_metrics')
        ).return_value = _succeed(True)
        stack.enter_context(mock.patch.object(collector, '_vmware_get_datastores')).return_value = _succeed(True)
        stack.enter_context(mock.patch.object(collector, '_vmware_get_hosts')).return_value = _succeed(True)
        stack.enter_context(
            mock.patch.object(collector, '_vmware_get_host_perf_manager_metrics')
        ).return_value = _succeed(True)
        stack.enter_context(mock.patch.object(collector, '_vmware_disconnect')).return_value = _succeed(True)
        metrics = yield collector.collect()

    assert metrics[0].name == 'vmware_vm_power_state'
    assert metrics[-1].name == 'vmware_vm_snapshot_timestamp_seconds'
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_collect_deferred_error_works():
    collect_only = {
        'vms': True,
        'vmguests': True,
        'datastores': True,
        'hosts': True,
        'snapshots': True,
    }
    collector = VmwareCollector(
        '127.0.0.1',
        'root',
        'password',
        collect_only,
        5000,
        ignore_ssl=True,
    )
    collector.content = _succeed(mock.Mock())

    @defer.inlineCallbacks
    def _fake_get_vms(*args, **kwargs):
        yield None
        raise RuntimeError('An error has occurred')

    with contextlib.ExitStack() as stack:
        stack.enter_context(mock.patch.object(collector, '_vmware_get_vms')).side_effect = _fake_get_vms
        stack.enter_context(
            mock.patch.object(collector, '_vmware_get_vm_perf_manager_metrics')
        ).return_value = _succeed(None)
        stack.enter_context(mock.patch.object(collector, '_vmware_get_datastores')).return_value = _succeed(None)
        stack.enter_context(mock.patch.object(collector, '_vmware_get_hosts')).return_value = _succeed(None)
        stack.enter_context(mock.patch.object(collector, '_vmware_disconnect')).return_value = _succeed(None)

        with pytest.raises(defer.FirstError):
            yield collector.collect()
				 
			
0 Source File : test_twisted.py , under MIT License , by poppyred
			 
			         @pytest_twisted.inlineCallbacks
    def test_health_service_subscribe(self, consul_port):
        c = consul.twisted.Consul(port=consul_port)

        class Config(object):
            def __init__(self):
                self.nodes = []
                self.index = None

            @defer.inlineCallbacks
            def update(self):
                self.index, nodes = yield c.health.service(
                    'foo', index=None, passing=True)
                self.nodes = [node['Service']['ID'] for node in nodes]

        config = Config()
        yield c.agent.service.register(
            'foo', service_id='foo:1', check=Check.ttl('40ms'))
        yield config.update()
        assert config.nodes == []

        # ping the service's health check
        yield c.agent.check.ttl_pass('service:foo:1')
        yield config.update()
        assert config.nodes == ['foo:1']

        # the service should fail
        yield sleep(0.8)
        yield config.update()
        assert config.nodes == []

        yield c.agent.service.deregister('foo:1')
				 
			
			 
			     @pytest.mark.twisted
@pytest_twisted.inlineCallbacks
def test_crash(localhost, ipdevpoll_test_config, pool):
    with pytest.raises(jobs.AbortedJobError):
        yield pool.execute_job('noop', localhost.pk, ['crash', ], 0)
				 
			
0 Source File : test_twisted_acl.py , under MIT License , by poppyred
			 
			         @pytest_twisted.inlineCallbacks
    def test_acl(self, acl_consul):
        c = consul.twisted.Consul(
            port=acl_consul.port, token=acl_consul.token)

        rules = """
            key "" {
                policy = "read"
            }
            key "private/" {
                policy = "deny"
            }
        """
        token = yield c.acl.create(rules=rules)

        raised = False
        try:
            yield c.acl.list(token=token)
        except consul.ACLPermissionDenied:
            raised = True
        assert raised

        destroyed = yield c.acl.destroy(token)
        assert destroyed is True

        query_service = 'foo'
        query_name = 'fooquery'
        query = yield c.query.create(query_service,
                                     query_name, token=acl_consul.token)

        # assert response contains query ID
        assert 'ID' in query \
               and query['ID'] is not None \
               and str(query['ID']) != ''
				 
			
			 
			     @pytest.mark.twisted
@pytest_twisted.inlineCallbacks
def test_fail(localhost, ipdevpoll_test_config, pool):
    res = yield pool.execute_job('noop', localhost.pk, ['fail', ], 0)
    assert res is True  # TODO: Check job status in database
				 
			
0 Source File : test_twisted.py , under MIT License , by poppyred
			 
			         @pytest_twisted.inlineCallbacks
    def test_agent_services(self, consul_port):
        c = consul.twisted.Consul(port=consul_port)
        services = yield c.agent.services()
        assert services == {}
        response = yield c.agent.service.register('foo')
        assert response is True
        services = yield c.agent.services()
        assert services == {'foo': {'ID': 'foo',
                                    'Service': 'foo',
                                    'Tags': [],
                                    'Meta': {},
                                    'Port': 0,
                                    'Address': '',
                                    'Weights': {'Passing': 1, 'Warning': 1},
                                    'EnableTagOverride': False
                                    }
                            }
        response = yield c.agent.service.deregister('foo')
        assert response is True
        services = yield c.agent.services()
        assert services == {}
				 
			
			 
			     @pytest.mark.twisted
@pytest_twisted.inlineCallbacks
def test_success(localhost, ipdevpoll_test_config, pool):
    res = yield pool.execute_job('noop', localhost.pk, ['noop', ], 0)
    assert res is True
				 
			
0 Source File : test_twisted.py , under MIT License , by poppyred
			 
			         @pytest_twisted.inlineCallbacks
    def test_catalog(self, consul_port):
        c = consul.twisted.Consul(port=consul_port)

        @defer.inlineCallbacks
        def register():
            response = yield c.catalog.register('n1', '10.1.10.11')
            assert response is True
            yield sleep(50 / 1000.0)
            response = yield c.catalog.deregister('n1')
            assert response is True

        reactor.callLater(1.0 / 100, register)

        index, nodes = yield c.catalog.nodes()
        assert len(nodes) == 1
        current = nodes[0]

        index, nodes = yield c.catalog.nodes(index=index)
        nodes.remove(current)
        assert [x['Node'] for x in nodes] == ['n1']

        index, nodes = yield c.catalog.nodes(index=index)
        nodes.remove(current)
        assert [x['Node'] for x in nodes] == []
				 
			
			 
			     @pytest.mark.twisted
@pytest_twisted.inlineCallbacks
def test_reschedule(localhost, ipdevpoll_test_config, pool):
    with pytest.raises(jobs.SuggestedReschedule):
        yield pool.execute_job('noop', localhost.pk, ['snmpcheck', ], 0)
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_vmware_resource_async_render_GET_section():
    request = mock.Mock()
    request.args = {
        b'target': [b'this-is-ignored'],
        b'section': [b'mysection'],
    }

    args = mock.Mock()
    args.config_file = None

    resource = VMWareMetricsResource(args)
    resource.config = {
        'default': {
            'ignore_ssl': False,
            'vsphere_host': '127.0.0.10',
            'vsphere_user': 'username1',
            'vsphere_password': 'password1',
            'specs_size': 5000,
            'collect_only': {
                'datastores': True,
                'hosts': True,
                'snapshots': True,
                'vmguests': True,
                'vms': True,
            }
        },
        'mysection': {
            'ignore_ssl': 'On',
            'vsphere_host': '127.0.0.11',
            'vsphere_user': 'username2',
            'vsphere_password': 'password2',
            'specs_size': 5000,
            'collect_only': {
                'datastores': True,
                'hosts': True,
                'snapshots': True,
                'vmguests': True,
                'vms': True,
            }
        }
    }

    with mock.patch('vmware_exporter.vmware_exporter.VmwareCollector') as Collector:
        Collector.return_value.collect.return_value = []
        yield resource._async_render_GET(request)

    Collector.assert_called_with(
        '127.0.0.11',
        'username2',
        'password2',
        resource.config['mysection']['collect_only'],
        5000,
        'On'
    )

    request.setResponseCode.assert_called_with(200)
    request.write.assert_called_with(b'')
    request.finish.assert_called_with()
				 
			
			 
			     @pytest.mark.twisted
@pytest_twisted.inlineCallbacks
def test_short_outage(localhost, db):
    plugin_registry['snmpcheck'] = snmpcheck.SnmpCheck
    job = JobHandler('snmpcheck', localhost.pk, plugins=['snmpcheck'])
    agent = Mock()
    job.agent = agent
    job._create_agentproxy = Mock()
    job._destroy_agentproxy = Mock()
    agent.walk.return_value = defer.succeed(False)
    with pytest.raises(SuggestedReschedule):
        yield job.run()
    assert agent.walk.called
    assert localhost.info_set.filter(
        key=snmpcheck.INFO_KEY_NAME,
        variable=snmpcheck.INFO_VARIABLE_NAME,
        value="down").exists()
    assert EventQueue.objects.filter(
        source_id='ipdevpoll',
        target_id='eventEngine',
        event_type='snmpAgentState',
        netbox_id=localhost.pk,
        state=EventQueue.STATE_START).count() == 1
    with pytest.raises(SuggestedReschedule):
        yield job.run()
    assert localhost.info_set.filter(
        key=snmpcheck.INFO_KEY_NAME,
        variable=snmpcheck.INFO_VARIABLE_NAME,
        value="down").exists()
    assert EventQueue.objects.filter(
        source_id='ipdevpoll',
        target_id='eventEngine',
        event_type='snmpAgentState',
        netbox_id=localhost.pk,
        state=EventQueue.STATE_START).count() == 2

    # now fake an AlertHist entry from event engine
    AlertHistory(
        source_id='ipdevpoll',
        event_type_id='snmpAgentState',
        netbox_id=localhost.pk,
        start_time=datetime.now(),
        end_time=INFINITY,
        value=100,
        severity=50,
    ).save()

    # and make sure snmpcheck tries to resolve it when the box is up
    agent.walk.return_value = defer.succeed(True)
    yield job.run()
    assert localhost.info_set.filter(
        key=snmpcheck.INFO_KEY_NAME,
        variable=snmpcheck.INFO_VARIABLE_NAME,
        value="up").exists()
    assert EventQueue.objects.filter(
        source_id='ipdevpoll',
        target_id='eventEngine',
        event_type='snmpAgentState',
        netbox_id=localhost.pk,
        state=EventQueue.STATE_END).count() == 1
				 
			
			 
			     @pt.inlineCallbacks
def test_get_cert_from_running_seed_node(ursula_federated_test_config):
    lonely_ursula_maker = partial(make_federated_ursulas,
                                  ursula_config=ursula_federated_test_config,
                                  quantity=1,
                                  know_each_other=False)

    firstula = lonely_ursula_maker().pop()
    node_deployer = firstula.get_deployer()

    node_deployer.addServices()
    node_deployer.catalogServers(node_deployer.hendrix)
    node_deployer.start()

    certificate_as_deployed = node_deployer.cert.to_cryptography()

    firstula_as_seed_node = firstula.seed_node_metadata()
    any_other_ursula = lonely_ursula_maker(seed_nodes=[firstula_as_seed_node],
                                           network_middleware=RestMiddleware()).pop()
    assert not any_other_ursula.known_nodes

    def start_lonely_learning_loop():
        any_other_ursula.log.info(
            "Known nodes when starting learning loop were: {}".format(any_other_ursula.known_nodes))
        any_other_ursula.start_learning_loop()
        result = any_other_ursula.block_until_specific_nodes_are_known(set([firstula.checksum_address]),
                                                                       timeout=2)
        assert result

    yield deferToThread(start_lonely_learning_loop)
    assert firstula in any_other_ursula.known_nodes

    firstula_as_learned = any_other_ursula.known_nodes[firstula.checksum_address]
    assert certificate_as_deployed == firstula_as_learned.certificate
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_collect_datastore():
    collect_only = {
        'vms': True,
        'vmguests': True,
        'datastores': True,
        'hosts': True,
        'snapshots': True,
    }
    collector = VmwareCollector(
        '127.0.0.1',
        'root',
        'password',
        collect_only,
        5000,
    )
    collector.content = _succeed(mock.Mock())

    collector.__dict__['datastore_labels'] = _succeed({
        'datastore-1': ['datastore-1', 'dc', 'ds_cluster'],
    })

    metrics = collector._create_metric_containers()

    with mock.patch.object(collector, 'batch_fetch_properties') as batch_fetch_properties:
        batch_fetch_properties.return_value = _succeed({
            'datastore-1': {
                'name': 'datastore-1',
                'summary.capacity': 0,
                'summary.freeSpace': 0,
                'host': ['host-1'],
                'vm': ['vm-1'],
                'summary.accessible': True,
                'summary.maintenanceMode': 'normal',
            }
        })

        yield collector._vmware_get_datastores(metrics)
        assert _check_properties(batch_fetch_properties.call_args[0][1])

    assert metrics['vmware_datastore_capacity_size'].samples[0][1] == {
        'ds_name': 'datastore-1',
        'dc_name': 'dc',
        'ds_cluster': 'ds_cluster'
    }
    assert metrics['vmware_datastore_capacity_size'].samples[0][2] == 0.0

    assert metrics['vmware_datastore_maintenance_mode'].samples[0][1] == {
        'ds_name': 'datastore-1',
        'dc_name': 'dc',
        'ds_cluster': 'ds_cluster',
        'mode': 'normal'
    }
    assert metrics['vmware_datastore_maintenance_mode'].samples[0][2] == 1.0

    assert metrics['vmware_datastore_accessible'].samples[0][1] == {
        'ds_name': 'datastore-1',
        'dc_name': 'dc',
        'ds_cluster': 'ds_cluster'
    }
    assert metrics['vmware_datastore_accessible'].samples[0][2] == 1.0
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_federated_nodes_connect_via_tls_and_verify(ursula_federated_test_config):
    node = make_federated_ursulas(ursula_config=ursula_federated_test_config, quantity=1).pop()
    node_deployer = node.get_deployer()

    node_deployer.addServices()
    node_deployer.catalogServers(node_deployer.hendrix)
    node_deployer.start()

    cert = node_deployer.cert.to_cryptography()
    cert_bytes = cert.public_bytes(serialization.Encoding.PEM)

    def check_node_with_cert(node, cert_file):
        response = requests.get("https://{}/public_information".format(node.rest_url()), verify=cert_file)
        ursula = Ursula.from_bytes(response.content, federated_only=True)
        assert ursula == node

    try:
        with open("test-cert", "wb") as f:
            f.write(cert_bytes)
        yield threads.deferToThread(check_node_with_cert, node, "test-cert")
    finally:
        os.remove("test-cert")
				 
			
			 
			     @pt.inlineCallbacks
def test_one_node_stores_a_bunch_of_others(federated_ursulas, ursula_federated_test_config):
    the_chosen_seednode = list(federated_ursulas)[2]  # ...neo?
    seed_node = the_chosen_seednode.seed_node_metadata()

    newcomer = make_federated_ursulas(
        ursula_config=ursula_federated_test_config,
        quantity=1,
        know_each_other=False,
        save_metadata=True,
        seed_nodes=[seed_node]).pop()

    assert not newcomer.known_nodes

    newcomer.start_learning_loop(now=True)

    def start_lonely_learning_loop():
        newcomer.start_learning_loop()
        start = maya.now()
        # Loop until the_chosen_seednode is in storage.
        while the_chosen_seednode not in newcomer.node_storage.all(federated_only=True):
            passed = maya.now() - start
            if passed.seconds > 2:
                pytest.fail("Didn't find the seed node.")

    yield deferToThread(start_lonely_learning_loop)

    assert list(newcomer.known_nodes)
    assert len(list(newcomer.known_nodes)) == len(list(newcomer.node_storage.all(True)))
    assert set(list(newcomer.known_nodes)) == set(list(newcomer.node_storage.all(True)))
				 
			
			 
			     @pt.inlineCallbacks
def test_run_lone_federated_default_development_ursula(click_runner):
    args = ('ursula', 'run',                            # Stat Ursula Command
            '--debug',                                  # Display log output; Do not attach console
            '--federated-only',                         # Operating Mode
            '--rest-port', MOCK_URSULA_STARTING_PORT,   # Network Port
            '--dev',                                    # Run in development mode (ephemeral node)
            '--dry-run',                                # Disable twisted reactor in subprocess
            '--lonely'                                  # Do not load seednodes
            )

    result = yield threads.deferToThread(click_runner.invoke,
                                         nucypher_cli, args,
                                         catch_exceptions=False,
                                         input=INSECURE_DEVELOPMENT_PASSWORD + '\n')

    time.sleep(Learner._SHORT_LEARNING_DELAY)
    assert result.exit_code == 0
    assert "Running" in result.output
    assert "127.0.0.1:{}".format(MOCK_URSULA_STARTING_PORT) in result.output

    reserved_ports = (UrsulaConfiguration.DEFAULT_REST_PORT, UrsulaConfiguration.DEFAULT_DEVELOPMENT_REST_PORT)
    assert MOCK_URSULA_STARTING_PORT not in reserved_ports
				 
			
			 
			     @pytest_twisted.inlineCallbacks
# @pytest.mark.skip
def test_metrics_without_hostaccess():
    boot_time = EPOCH + datetime.timedelta(seconds=60)
    disk = mock.Mock()
    disk.diskPath = '/boot'
    disk.capacity = 100
    disk.freeSpace = 50

    collect_only = {
        'vms': True,
        'vmguests': True,
        'datastores': False,
        'hosts': False,
        'snapshots': False,
    }

    collector = VmwareCollector(
        '127.0.0.1',
        'root',
        'password',
        collect_only,
        5000,
    )
    metrics = collector._create_metric_containers()
    collector.content = _succeed(mock.Mock())
    collector.__dict__['host_labels'] = _succeed({'': []})

    with mock.patch.object(collector, 'batch_fetch_properties') as batch_fetch_properties:
        batch_fetch_properties.return_value = _succeed({
            'vm-1': {
                'name': 'vm-x',
                'runtime.host': vim.ManagedObject('notfound:1'),
                'runtime.powerState': 'poweredOn',
                'summary.config.numCpu': 1,
                'summary.config.memorySizeMB': 1024,
                'runtime.maxCpuUsage': 2400,
                'summary.config.template': False,
                'runtime.bootTime': boot_time,
                'guest.disk': [disk],
                'guest.toolsStatus': 'toolsOk',
                'guest.toolsVersion': '10336',
                'guest.toolsVersionStatus2': 'guestToolsUnmanaged',
            }
        })
        assert collector.vm_labels.result == {'vm-1': ['vm-x']}
        yield collector._vmware_get_vms(metrics)

        # 113 AssertionError {'partition': '/boot'} vs {'host_name': '/boot'}
        assert metrics['vmware_vm_guest_disk_capacity'].samples[0][1] == {
            'vm_name': 'vm-x',
            'partition': '/boot',
            'host_name': 'n/a',
            'cluster_name': 'n/a',
            'dc_name': 'n/a',
        }

        # Fail due to expected labels ['vm-1', 'host-1', 'dc', 'cluster-1']
        # but found ['vm-1']
        assert metrics['vmware_vm_power_state'].samples[0][1] == {
            'vm_name': 'vm-x',
            'host_name': 'n/a',
            'cluster_name': 'n/a',
            'dc_name': 'n/a',
        }