def deallocate_for_instance(self, context, **kwargs):
        instance_id = kwargs.get('instance_id')
        project_id = kwargs.pop('project_id', None)
        admin_context = context.elevated()
        networks = self._get_networks_for_instance(admin_context, instance_id,
                                                                  project_id)
        vifs = self.db.virtual_interface_get_by_instance(context, instance_id)
        for n in networks:
            vif_id = "nova-" + str(instance_id) + "-" + str(n['id'])
            # Un-attach the vif and delete the port
            tenant_id = project_id or FLAGS.quantum_default_tenant_id
            quantum_net_id = n['bridge']
            LOG.debug("Using quantum_net_id: %s" % quantum_net_id)
            attachment = vif_id
            port_id = quantum.get_port_by_attachment(tenant_id,
                                            quantum_net_id, attachment)

            # FIXME: tell Quantum that this interface-binding is no
            # longer valid.

            if not port_id:
                LOG.error("Unable to find port with attachment: %s" % \
                                                        (attachment))
            else:
                quantum.unplug_iface(tenant_id, quantum_net_id, port_id)
                quantum.delete_port(tenant_id, quantum_net_id, port_id)

            vif = filter(lambda vif: vif['network_id'] == n['id'], vifs)[0]
            melange.deallocate_ips(n['id'], vif['id'],
                                   project_id=n['project_id'])

        self.db.virtual_interface_delete_by_instance(context, instance_id)
    def _setup_quantum_mocks(self):
        self.mox.StubOutWithMock(quantum, "get_port_by_attachment")
        self.mox.StubOutWithMock(quantum, "unplug_iface")
        self.mox.StubOutWithMock(quantum, "delete_port")

        quantum.get_port_by_attachment(IgnoreArg(), IgnoreArg(), IgnoreArg()).\
                                           MultipleTimes().AndReturn("port_id")
        quantum.unplug_iface(IgnoreArg(), IgnoreArg(), IgnoreArg()).\
                                          MultipleTimes()
        quantum.delete_port(IgnoreArg(), IgnoreArg(), IgnoreArg()).\
                                         MultipleTimes()