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

3 Source File : test_adtran_netconf.py , under Apache License 2.0 , by opencord
			 
			     @pytest_twisted.inlineCallbacks
def test_rpc(test_client):
    test_client._session = mock.MagicMock()
    with mock.patch("voltha.adapters.adtran_olt.net.adtran_netconf.etree") as mock_etree:
        yield test_client.rpc("<rpc>xml</rpc>")
        mock_etree.fromstring.assert_called_once_with("<rpc>xml</rpc>")
				 
			
3 Source File : test_onu_gem_port.py , under Apache License 2.0 , by opencord
			 
			     @pytest_twisted.inlineCallbacks
def test_add_to_hardware_isMock():
    """
    verify call to add hardware when isMock = True
    """
    _isMock = True

    mock_handler = MagicMock()
    mock_handler.device_id = MOCK_HANDLER_DEVICE_ID

    ogp = OnuGemPort(mock_handler, GEM_DATA, ALLOCID, TECHPROFILEID, UNIID, ENTITYID, MULTICAST, TRAFFICCLASS,
                     _isMock)

    result = yield ogp.add_to_hardware('fake', 'fake', 'fake', 'fake')
    assert result == 'mock'
				 
			
3 Source File : test_adtran_netconf.py , under Apache License 2.0 , by opencord
			 
			     @pytest_twisted.inlineCallbacks
def test_rpc_session_reconnect(test_client):
    test_client._session = mock.MagicMock()
    test_client._session.connected = False
    with mock.patch.object(test_client, "_reconnect") as mock_reconnect:
        yield test_client.rpc("<rpc>xml</rpc>")
        mock_reconnect.assert_called_once()
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_check_confirms():
    """Assert confirmations are enabled by default."""
    serv = service.FedoraMessagingService(amqp_url="amqp://")
    serv.startService()
    client = yield serv.getFactory().whenConnected()
    channel = yield client._allocate_channel()
    assert channel._delivery_confirmation is True
    serv.stopService()
				 
			
3 Source File : test_onu_tcont.py , under Apache License 2.0 , by opencord
			 
			     @pytest_twisted.inlineCallbacks
def test_remove_mock_onu_tcont_from_hardware(tcont_fixture):
    with mock.patch("voltha.extensions.omci.omci_cc") as omci:
        tcont_fixture._is_mock = True
        output = yield tcont_fixture.remove_from_hardware(omci)
        assert output == "mock"
				 
			
3 Source File : test_olt_gem_port.py , under Apache License 2.0 , by opencord
			 
			     @pytest_twisted.inlineCallbacks
def test_remove_from_hardware_ismock():
    """
    verify call to remove hardware when isMock = True
    """

    _isMock = True

    ogp = OltGemPort(GEMID, ALLOCID, TECHPROFILEID, PONID, ONUID, UNIID, ENCRYPTION, MULTICAST, TRAFFICCLASS, HANDLER,
                     _isMock)

    result = yield ogp.remove_from_hardware('session')
    assert result == 'mock'
				 
			
3 Source File : test_adtran_netconf.py , under Apache License 2.0 , by opencord
			 
			     @pytest_twisted.inlineCallbacks
def test_close(test_client):
    mock_session = mock.MagicMock()
    test_client._session = mock_session
    mock_session.connected = True
    yield test_client.close()
    mock_session.close_session.assert_called_once_with()
				 
			
3 Source File : test_adtran_rest.py , under Apache License 2.0 , by opencord
			 
			     @pytest_twisted.inlineCallbacks
def test_404_on_post(test_client, mock_treq):
    mock_treq.post.side_effect = [MockResponse(404)]
    with pytest.raises(RestInvalidResponseCode,
                       message="REST POST '' request to 'http://1.2.3.4:80/test/uri' failed with status code 404"):
        yield test_client.request("POST", "/test/uri", SOME_JSON)
				 
			
			 
			     @mark.parametrize("install_by_delete", [True, False])
@pytest_twisted.inlineCallbacks
def test_perform_flow_install(flow_task, install_by_delete, mock_res):
    flow_task.check_status_and_state = Mock()
    flow_task._onu_device.omci_cc.send = Mock()
    flow_task._install_by_delete = install_by_delete
    flow_task._onu_device.omci_cc.send.return_value = 'test'
    yield flow_task.perform_flow_install()
    if install_by_delete:
        flow_task.check_status_and_state.assert_any_call('test', operation='delete')
        flow_task.check_status_and_state.assert_any_call('test', 'flow-recreate-before-set')
    flow_task.check_status_and_state.assert_any_call('test', 'set-extended-vlan-tagging-operation-configuration-data')
    flow_task.check_status_and_state.assert_any_call('test', 'flow-set-ext-vlan-tagging-op-config-data-untagged')
				 
			
3 Source File : test_onu_tcont.py , under Apache License 2.0 , by opencord
			 
			     @pytest_twisted.inlineCallbacks
def test_remove_onu_tcont_from_hardware_exception(tcont_fixture):
    with mock.patch("voltha.extensions.omci.omci_cc") as omci:
        tcont_fixture._is_mock = False
        omci.send.side_effect = Exception
        with pytest.raises(Exception):
            yield tcont_fixture.remove_from_hardware(omci)
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_declare_exchange_failures():
    """Assert that if an exchange can't be declared, it results in an exception."""
    serv = service.FedoraMessagingService(amqp_url="amqp://")
    serv.startService()
    client = yield serv.getFactory().whenConnected()

    exchanges = [{"exchange": str(uuid.uuid4()), "passive": True}]
    try:
        yield client.declare_exchanges(exchanges)
    except exceptions.BadDeclaration as e:
        assert "exchange" == e.obj_type
        assert exchanges[0] == e.description
        assert isinstance(e.reason, pika.exceptions.ChannelClosed)
    yield serv.stopService()
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_make_netconf_connection(simple_handler):
    AdtranDeviceHandler.NC_CLIENT = AdtranNetconfClient
    with mock.patch('voltha.adapters.adtran_olt.net.adtran_netconf.AdtranNetconfClient.connect'):
        yield simple_handler.make_netconf_connection()
        assert isinstance(simple_handler.netconf_client, AdtranNetconfClient)
        first_client = simple_handler.netconf_client

        yield simple_handler.make_netconf_connection(close_existing_client=True)
        assert isinstance(simple_handler.netconf_client, AdtranNetconfClient)
        assert first_client is not simple_handler.netconf_client
				 
			
			 
			     @pytest.mark.twisted
@pytest_twisted.inlineCallbacks
def test_do_check_should_report_false_on_timeout(plugin):
    plugin.agent.walk.return_value = defer.fail(defer.TimeoutError())
    res = yield plugin._do_check()
    assert res is False
				 
			
			 
			     @pytest.mark.twisted
@pytest_twisted.inlineCallbacks
def test_should_mark_as_up_when_transitioning_from_down_to_up(plugin):
    plugin._currently_down = Mock(return_value=True)
    plugin._currently_down.__name__ = '_currently_down'
    plugin.agent.walk.return_value = defer.succeed(True)
    plugin._mark_as_up = Mock()
    plugin._mark_as_down = Mock()
    yield plugin.handle()
    plugin._mark_as_down.assert_not_called()
    plugin._mark_as_up.assert_called()
				 
			
3 Source File : test_adtran_rest.py , under Apache License 2.0 , by opencord
			 
			     @pytest_twisted.inlineCallbacks
def test_bad_json(test_client, mock_treq):
    mock_resp = MockResponse(200)
    mock_treq.post.side_effect = [mock_resp]
    mock_resp.headers.hasHeader.return_value = True
    mock_resp.headers.getRawHeaders.return_value = ['application/json']
    mock_resp.content.return_value = """{"other": "json}"""
    with pytest.raises(ValueError):
        yield test_client.request("POST", "/test/uri", SOME_JSON)
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_reboot(simple_handler, device):
    device.oper_status = OperStatus.ACTIVE
    device.connect_status = ConnectStatus.REACHABLE
    simple_handler._initial_enable_complete = True
    yield simple_handler.make_netconf_connection()
    yield simple_handler.reboot()
    simple_handler._cancel_tasks()
    assert device.oper_status == OperStatus.ACTIVATING
    assert device.connect_status == ConnectStatus.UNREACHABLE
				 
			
3 Source File : test_adtran_netconf.py , under Apache License 2.0 , by opencord
			 
			     @pytest_twisted.inlineCallbacks
def test_edit_config_without_config_at_start_of_xml(test_client):
    test_client._session = mock.MagicMock()
    test_client._session.edit_config.return_value = "<ok>"
    yield test_client.edit_config("")
    test_client._session.edit_config.assert_called_once_with(
        target="running",
        config='<config xmlns:xc="urn:ietf:params:xml:ns:netconf:base:1.0" xmlns="urn:ietf:params:xml:ns:netconf:base:1.0"></config>')
				 
			
0 Source File : test_adtran_rest.py , under Apache License 2.0 , by opencord
			 
			     @pytest_twisted.inlineCallbacks
def test_literally_any_other_exception(test_client, mock_treq):
    mock_treq.post.side_effect = SyntaxError()
    with pytest.raises(SyntaxError):
        yield test_client.request("POST", "/test/uri", SOME_JSON, is_retry=True)
				 
			
0 Source File : test_onu_gem_port.py , under Apache License 2.0 , by opencord
			 
			     @patch('voltha.adapters.adtran_onu.onu_gem_port.GemInterworkingTpFrame')
@patch('voltha.adapters.adtran_onu.onu_gem_port.GemPortNetworkCtpFrame')
@patch('voltha.adapters.adtran_onu.onu_gem_port.structlog.get_logger')
@pytest_twisted.inlineCallbacks
def test_add_to_hardware_exceptions_gem_port_failed_and_try_except(patched_get_logger, ctp_class, tp_class):
    """
    verify add hardware exception

    Ctp section - Tests Reason Code not equal to Success, GEM Port creation FAILED

    AND tests try/except logic of the CtpFrame section
    """
    ctp_class.return_value.create.return_value = 'CtpFrame Create Success!'
    tp_class.return_value.create.return_value = 'TpFrame Create Success!'

    _ = patched_get_logger

    # create mock for handler
    mock_handler = MagicMock()
    mock_handler.device_id = MOCK_HANDLER_DEVICE_ID

    # CREATE the class object to be tested, send it the mock handler
    ogp = ogp_defaults(mock_handler)

    # PREPARE to call the add_hardware method

    # prepare nested 'fields' result for omci.send
    class MockResults(object):
        def __init__(self, expected_output):
            self.fields = expected_output

    mock_send_result = MockResults({'omci_message': MockResults({'success_code': 0,
                                                                 'parameter_error_attributes_mask': 1234})})

    # create mock for omci
    mock_omci = MagicMock()
    mock_omci.send.return_value = mock_send_result  # omci.send() will return the nested 'fields' structure


    # create problem
    mock_send_result = MockResults({'omci_message': MockResults({'success_code': 2,
                                                                 'parameter_error_attributes_mask': 1234})})
    mock_omci.send.return_value = mock_send_result

    with pytest.raises(Exception) as caught_ex:
        yield ogp.add_to_hardware(mock_omci, TCONTENTITYID, IEEEENTITYID, GALENETENTITYID)

    # verify the raise
    assert caught_ex.typename == 'Exception'
    assert caught_ex.value.message == 'GEM Port create failed with status: 2'
				 
			
0 Source File : test_onu_gem_port.py , under Apache License 2.0 , by opencord
			 
			     @patch('voltha.adapters.adtran_onu.onu_gem_port.GemInterworkingTpFrame')
@patch('voltha.adapters.adtran_onu.onu_gem_port.GemPortNetworkCtpFrame')
@patch('voltha.adapters.adtran_onu.onu_gem_port.structlog.get_logger')
@pytest_twisted.inlineCallbacks
def test_remove_from_hardware(patched_get_logger, ctp_class, tp_class):
    """
    verify call to remove hardware when isMock = False
    """

    ctp_class.return_value.delete.return_value = 'CtpFrame Delete Success!'
    tp_class.return_value.delete.return_value = 'TpFrame Delete Success!'

    _ = patched_get_logger

    # create mock for handler
    mock_handler = MagicMock()
    mock_handler.device_id = MOCK_HANDLER_DEVICE_ID

    # CREATE the class object to be tested, send it the mock handler
    ogp = ogp_defaults(mock_handler)

    # adjust some class instance attributes so remove_hardware will run
    ogp._interworking = True
    ogp._tcont_entity_id = 1  # not None

    # PREPARE to call the remove_hardware method

    # prepare nested 'fields' result for omci.send
    class MockResults(object):
        def __init__(self, expected_output):
            self.fields = expected_output

    mock_send_result = MockResults({'omci_message': MockResults({'success_code': 0})})

    # create mock for omci
    mock_omci = MagicMock()
    mock_omci.send.return_value = mock_send_result   # omci.send() will return the nested 'fields' structure

    # make the call to remove_from_hardware
    result = yield ogp.remove_from_hardware(mock_omci)

    # VERIFY Results
    assert result == mock_send_result

    assert ogp.log.debug.call_count == 3

    ogp.log.debug.assert_any_call('remove-from-hardware', gem_id=GEM_DATA.get('gemport-id'))

    ctp_class.assert_called_once_with(ENTITYID)

    mock_omci.send.assert_any_call('CtpFrame Delete Success!')

    # the following validates the log entry and the mock_send_result from omci.send() after GemPortNetworkCtpFrame
    ogp.log.debug.assert_any_call('delete-gem-port-network-ctp', status=0)

    assert ogp._tcont_entity_id is None

    tp_class.assert_called_once_with(ENTITYID)

    mock_omci.send.assert_any_call('TpFrame Delete Success!')

    # the following validates the log entry and the mock_send_result from omci.send() after GemInterworkingTpFrame
    ogp.log.debug.assert_any_call('delete-gem-interworking-tp', status=0)

    assert ogp._interworking is False
				 
			
0 Source File : test_adtran_netconf.py , under Apache License 2.0 , by opencord
			 
			     @pytest_twisted.inlineCallbacks
def test_unlock(test_client):
    test_client._session = mock.MagicMock()
    yield test_client.unlock("running")
    test_client._session.unlock.assert_called_once_with("running")
				 
			
0 Source File : test_adtran_rest.py , under Apache License 2.0 , by opencord
			 
			     @pytest_twisted.inlineCallbacks
def test_connection_closed(test_client, mock_treq):
    mock_treq.post.side_effect = ConnectionClosed()
    output = yield test_client.request("POST", "/test/uri", SOME_JSON)
    assert output == ConnectionClosed
				 
			
0 Source File : test_onu_gem_port.py , under Apache License 2.0 , by opencord
			 
			     @patch('voltha.adapters.adtran_onu.onu_gem_port.structlog.get_logger')
@pytest_twisted.inlineCallbacks
def test_add_to_hardware_exceptions_bad_tcont(patched_get_logger):
    """
    verify add hardware errors and exception

    Ctp Section - Tests call to add_to_hardware with a bad tcont_entity_id
    """

    _ = patched_get_logger

    # create mock for handler
    mock_handler = MagicMock()
    mock_handler.device_id = MOCK_HANDLER_DEVICE_ID

    # CREATE the class object to be tested, send it the mock handler
    ogp = ogp_defaults(mock_handler)

    # PREPARE to call the add_hardware method

    # prepare nested 'fields' result for omci.send
    class MockResults(object):
        def __init__(self, expected_output):
            self.fields = expected_output

    mock_send_result = MockResults({'omci_message': MockResults({'success_code': 0,
                                                                 'parameter_error_attributes_mask': 1234})})

    # create mock for omci
    mock_omci = MagicMock()
    mock_omci.send.return_value = mock_send_result  # omci.send() will return the nested 'fields' structure

    # create problem
    ogp._tcont_entity_id = 999

    with pytest.raises(Exception) as caught_ex:
        yield ogp.add_to_hardware(mock_omci, TCONTENTITYID, IEEEENTITYID, GALENETENTITYID)

    # verify the raise
    assert caught_ex.typename == 'KeyError'
    assert caught_ex.value.message == 'GEM Port already assigned to TCONT: 999'

    # undo problem
    ogp._tcont_entity_id = None
				 
			
0 Source File : test_onu_gem_port.py , under Apache License 2.0 , by opencord
			 
			     @patch('voltha.adapters.adtran_onu.onu_gem_port.GemInterworkingTpFrame')
@patch('voltha.adapters.adtran_onu.onu_gem_port.GemPortNetworkCtpFrame')
@patch('voltha.adapters.adtran_onu.onu_gem_port.structlog.get_logger')
@pytest_twisted.inlineCallbacks
def test_add_to_hardware(patched_get_logger, ctp_class, tp_class):
    """
    verify call to add hardware when isMock = False
    """
    ctp_class.return_value.create.return_value = 'CtpFrame Create Success!'
    tp_class.return_value.create.return_value = 'TpFrame Create Success!'

    _ = patched_get_logger

    # create mock for handler
    mock_handler = MagicMock()
    mock_handler.device_id = MOCK_HANDLER_DEVICE_ID

    # CREATE the class object to be tested, send it the mock handler
    ogp = ogp_defaults(mock_handler)

    # PREPARE to call the add_hardware method

    # prepare nested 'fields' result for omci.send
    class MockResults(object):
        def __init__(self, expected_output):
            self.fields = expected_output

    mock_send_result = MockResults({'omci_message': MockResults({'success_code': 0,
                                    'parameter_error_attributes_mask': 1234})})

    # create mock for omci
    mock_omci = MagicMock()
    mock_omci.send.return_value = mock_send_result   # omci.send() will return the nested 'fields' structure

    # Test values before in_hardware
    assert ogp.in_hardware is False

    # make the call to add_to_hardware
    result = yield ogp.add_to_hardware(mock_omci, TCONTENTITYID, IEEEENTITYID, GALENETENTITYID)

    # Test values after in_hardware
    assert ogp.in_hardware is True

    # VERIFY Results

    assert result == mock_send_result

    assert ogp.log.debug.call_count == 3

    ogp.log.debug.assert_any_call('add-to-hardware',
                                  gem_id=GEM_DATA.get('gemport-id'),
                                  gem_entity_id=ENTITYID,
                                  tcont_entity_id=TCONTENTITYID,
                                  ieee_mapper_service_profile_entity_id=IEEEENTITYID,
                                  gal_enet_profile_entity_id=GALENETENTITYID)

    ctp_class.assert_called_once_with(ENTITYID,
                                      port_id=GEM_DATA.get('gemport-id'),
                                      tcont_id=TCONTENTITYID,
                                      direction='bi-directional',
                                      upstream_tm=0x8000)

    mock_omci.send.assert_any_call('CtpFrame Create Success!')

    # the following validates the log entry and the mock_send_result from omci.send() after GemPortNetworkCtpFrame
    ogp.log.debug.assert_any_call('create-gem-port-network-ctp', status=0, error_mask=1234)

    assert ogp._tcont_entity_id == TCONTENTITYID

    tp_class.assert_called_once_with(ENTITYID,
                                     gem_port_network_ctp_pointer=ENTITYID,
                                     interworking_option=5,
                                     service_profile_pointer=IEEEENTITYID,
                                     interworking_tp_pointer=0x0,
                                     pptp_counter=1,
                                     gal_profile_pointer=GALENETENTITYID,
                                     attributes={'gal_loopback_configuration': 0})

    mock_omci.send.assert_any_call('TpFrame Create Success!')

    # the following validates the log entry and the mock_send_result from omci.send() after GemInterworkingTpFrame
    ogp.log.debug.assert_any_call('create-gem-interworking-tp', status=0, error_mask=1234)

    assert ogp._interworking is True
				 
			
			 
			     @pytest_twisted.inlineCallbacks
def test_twisted_consume_halt_consumer_requeue(queue_and_binding):
    """Assert raising HaltConsumer with requeue=True re-queues the message."""
    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):
        """Count to 3 and quit."""
        raise exceptions.HaltConsumer(exit_code=1, requeue=True)

    # 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 as e:
        # Assert there are no consumers for the queue, and that there's a ready message
        assert e.exit_code == 1

        server_queue = yield get_queue(queues)
        assert server_queue["consumers"] == 0
        assert server_queue["messages_ready"] == 1
    except (defer.TimeoutError, defer.CancelledError):
        yield consumers[0].cancel()
        pytest.fail("Timeout reached without consumer halting!")
				 
			
			 
			     @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!")
				 
			
0 Source File : test_adtran_rest.py , under Apache License 2.0 , by opencord
			 
			     @pytest_twisted.inlineCallbacks
def test_connection_done(test_client, mock_treq):
    mock_treq.post.side_effect = ConnectionDone()
    with pytest.raises(ConnectionDone):
        yield test_client.request("POST", "/test/uri", SOME_JSON, is_retry=True)
				 
			
			 
			     @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_activate(simple_handler, device):
    @inlineCallbacks
    def mock_netconf_ready():
        yield
        returnValue('ready')

    @inlineCallbacks
    def enumerate_ports(_device):
        yield None
        returnValue([])

    simple_handler.ready_network_access = mock_netconf_ready
    simple_handler.enumerate_northbound_ports = enumerate_ports
    simple_handler.process_northbound_ports = lambda dev, results: 'ok'
    simple_handler.enumerate_southbound_ports = enumerate_ports
    simple_handler.process_southbound_ports = lambda dev, results: 'ok'
    simple_handler.initialize_resource_manager = lambda: 'done'
    simple_handler.complete_device_specific_activation = lambda dev, rec: succeed('Done')

    simple_handler._rest_client = mock.MagicMock(autospec=AdtranRestClient)
    simple_handler._rest_client.request = mock_restconf_request

    result = yield simple_handler.activate(None, False)
    assert result == 'activated'

    # Test Side Effects
    assert simple_handler.netconf_client is not None
    assert simple_handler.rest_client is not None
    assert simple_handler.logical_device_id == 'test-id'
    assert device.model == 'unknown'
    assert device.vendor == 'Adtran Inc.'

    # Reconcile
    simple_handler._delete_logical_device()
    result = yield simple_handler.activate(None, True)
    assert result == 'activated'
				 
			
0 Source File : test_adtran_netconf.py , under Apache License 2.0 , by opencord
			 
			     @pytest_twisted.inlineCallbacks
def test_get(test_client):
    test_client._session = mock.MagicMock()
    yield test_client.get("<get>xml</get>")
    test_client._session.get.assert_called_once_with("<get>xml</get>")
				 
			
0 Source File : test_adtran_netconf.py , under Apache License 2.0 , by opencord
			 
			     @pytest_twisted.inlineCallbacks
def test_unlock_with_no_session(test_client):
    test_client._session = None
    with pytest.raises(NotImplementedError):
        yield test_client.unlock("running")
				 
			
			 
			     @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)
				 
			
0 Source File : test_adtran_netconf.py , under Apache License 2.0 , by opencord
			 
			     @pytest_twisted.inlineCallbacks
def test_lock(test_client):
    test_client._session = mock.MagicMock()
    yield test_client.lock("running", 10)
    test_client._session.lock.assert_called_once_with("running", timeout=10)
				 
			
			 
			     @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_get_state(mock_session, pes_object):
    mock_session.get.return_value = "<some>xml</some>"
    output = yield pes_object.get_state()
    assert output == "<some>xml</some>"
				 
			
0 Source File : test_adtran_netconf.py , under Apache License 2.0 , by opencord
			 
			     @pytest_twisted.inlineCallbacks
def test_lock_with_no_session(test_client):
    test_client._session = None
    with pytest.raises(NotImplementedError):
        yield test_client.lock("running", 10)
				 
			
			 
			     @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!")
				 
			
0 Source File : test_adtran_netconf.py , under Apache License 2.0 , by opencord
			 
			     @pytest_twisted.inlineCallbacks
def test_edit_config_with_no_session(test_client):
    test_client._session = None
    with pytest.raises(NotImplementedError):
        yield test_client.edit_config("<some>config</some>")