'verify we will delete created ports
if we fail to allocate all net resources.
Mox to raise exception when creating a second port.
In this case, the code should delete the first created port.'

@mock.patch('nova.network.neutronv2.api.API._populate_neutron_extension_values')
@mock.patch('nova.network.neutronv2.api.API._has_port_binding_extension')
@mock.patch('nova.network.neutronv2.api.API._create_ports_for_instance')
@mock.patch('nova.network.neutronv2.api.API._unbind_ports')
def test_allocate_for_instance_ex1(self, mock_unbind, mock_create_ports, mock_has_port_binding, mock_populate):

    self.instance = fake_instance.fake_instance_obj(self.context, **self.instance)
    api = neutronapi.API()
    requested_networks = objects.NetworkRequestList(objects=[objects.NetworkRequest(network_id=net['id']) for net in (self.nets2[0], self.nets2[1])])
    neutronapi.get_client(mox.IgnoreArg()).AndReturn(self.moxed_client)
    self.moxed_client.list_networks(id=[uuids.my_netid1, uuids.my_netid2]).AndReturn({'networks': self.nets2})
    mock_has_port_binding.return_value = False
    mock_create_ports.return_value = [(request, getattr(uuids, ('portid_%s' % request.network_id))) for request in requested_networks]
    neutronapi.get_client(mox.IgnoreArg(), admin=True).AndReturn(self.moxed_client)
    index = 0
    for network in self.nets2:
        binding_port_req_body = {'port': {'device_id': self.instance.uuid, 'device_owner': 'compute:nova'}}
        port_req_body = {'port': {'network_id': network['id'], 'admin_state_up': True, 'tenant_id': self.instance.project_id}}
        port_req_body['port'].update(binding_port_req_body['port'])
        port_id = getattr(uuids, ('portid_%s' % network['id']))
        port = {'id': port_id, 'mac_address': 'foo'}
        if (index == 0):
            self.moxed_client.update_port(port_id, MyComparator(binding_port_req_body)).AndReturn({'port': port})
        else:
            NeutronOverQuota = exceptions.MacAddressInUseClient()
            self.moxed_client.update_port(port_id, MyComparator(binding_port_req_body)).AndRaise(NeutronOverQuota)
        index += 1
    self.moxed_client.delete_port(getattr(uuids, ('portid_%s' % self.nets2[0]['id'])))
    self.moxed_client.delete_port(getattr(uuids, ('portid_%s' % self.nets2[1]['id'])))
    self.mox.ReplayAll()
    self.assertRaises(exception.PortInUse, api.allocate_for_instance, self.context, self.instance, False, requested_networks=requested_networks)
    mock_unbind.assert_called_once_with(self.context, [], self.moxed_client, mock.ANY)
