Skip to content

Commit

Permalink
libvirt: convert LibvirtConnTestCase to use fakelibvirt fixture
Browse files Browse the repository at this point in the history
Instead of defining a custom fake libvirt class and installing
mocks for it, just use the standard fakelibvirt fixture.

Blueprint: libvirt-driver-class-refactor
Change-Id: I1b0e8d55ff498c57ff25e5d47078f59c95734dc6
  • Loading branch information
berrange committed Jan 22, 2015
1 parent 31d0f5a commit 4b9bec3
Show file tree
Hide file tree
Showing 2 changed files with 62 additions and 111 deletions.
45 changes: 44 additions & 1 deletion nova/tests/unit/virt/libvirt/fakelibvirt.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,6 +134,7 @@ def _reset():
VIR_FROM_NWFILTER = 330
VIR_FROM_REMOTE = 340
VIR_FROM_RPC = 345
VIR_FROM_NODEDEV = 666
VIR_ERR_NO_SUPPORT = 3
VIR_ERR_XML_DETAIL = 350
VIR_ERR_NO_DOMAIN = 420
Expand All @@ -143,6 +144,7 @@ def _reset():
VIR_ERR_SYSTEM_ERROR = 900
VIR_ERR_INTERNAL_ERROR = 950
VIR_ERR_CONFIG_UNSUPPORTED = 951
VIR_ERR_NO_NODE_DEVICE = 667

# Readonly
VIR_CONNECT_RO = 1
Expand Down Expand Up @@ -280,6 +282,30 @@ def undefine(self):
self._connection._remove_filter(self)


class NodeDevice(object):

def __init__(self, connection, xml=None):
self._connection = connection

self._xml = xml
if xml is not None:
self._parse_xml(xml)

def _parse_xml(self, xml):
tree = etree.fromstring(xml)
root = tree.find('.')
self._name = root.get('name')

def attach(self):
pass

def dettach(self):
pass

def reset(self):
pass


class Domain(object):
def __init__(self, connection, xml, running=False, transient=False):
self._connection = connection
Expand Down Expand Up @@ -643,6 +669,7 @@ def __init__(self, uri=None, readonly=False, version=9011):
self._running_vms = {}
self._id_counter = 1 # libvirt reserves 0 for the hypervisor.
self._nwfilters = {}
self._nodedevs = {}
self._event_callbacks = {}
self.fakeLibVersion = version
self.fakeVersion = version
Expand All @@ -653,6 +680,12 @@ def _add_filter(self, nwfilter):
def _remove_filter(self, nwfilter):
del self._nwfilters[nwfilter._name]

def _add_nodedev(self, nodedev):
self._nodedevs[nodedev._name] = nodedev

def _remove_nodedev(self, nodedev):
del self._nodedevs[nodedev._name]

def _mark_running(self, dom):
self._running_vms[self._id_counter] = dom
self._emit_lifecycle(dom, VIR_DOMAIN_EVENT_STARTED, 0)
Expand Down Expand Up @@ -1040,6 +1073,16 @@ def nwfilterDefineXML(self, xml):
nwfilter = NWFilter(self, xml)
self._add_filter(nwfilter)

def nodeDeviceLookupByName(self, name):
try:
return self._nodedevs[name]
except KeyError:
raise make_libvirtError(
libvirtError,
"no nodedev with matching name %s" % name,
error_code=VIR_ERR_NO_NODE_DEVICE,
error_domain=VIR_FROM_NODEDEV)

def listDefinedDomains(self):
return []

Expand Down Expand Up @@ -1115,7 +1158,7 @@ def make_libvirtError(error_class, msg, error_code=None,


virDomain = Domain

virNodeDevice = NodeDevice

virConnect = Connection

Expand Down
128 changes: 18 additions & 110 deletions nova/tests/unit/virt/libvirt/test_driver.py
Original file line number Diff line number Diff line change
Expand Up @@ -471,74 +471,7 @@ def fake_extend(image, size, use_cow=False):
self.stubs.Set(imagebackend.Image, 'resolve_driver_format',
imagebackend.Image._get_driver_format)

class FakeConn(object):
def baselineCPU(self, cpu, flag):
"""Add new libvirt API."""
return """<cpu mode='custom' match='exact'>
<model fallback='allow'>Westmere</model>
<vendor>Intel</vendor>
<feature policy='require' name='aes'/>
<feature policy='require' name='hypervisor'/>
</cpu>"""

def getCapabilities(self):
"""Ensure standard capabilities being returned."""
return """<capabilities>
<host><cpu><arch>x86_64</arch>
<feature policy='require' name='hypervisor'/>
</cpu></host>
</capabilities>"""

def getVersion(self):
return 1005001

def getLibVersion(self):
return (0 * 1000 * 1000) + (9 * 1000) + 11

def domainEventRegisterAny(self, *args, **kwargs):
pass

def registerCloseCallback(self, cb, opaque):
pass

def nwfilterDefineXML(self, *args, **kwargs):
pass

def nodeDeviceLookupByName(self, x):
pass

def listDevices(self, cap, flags):
return []

def lookupByName(self, name):
pass

def lookupByID(self, id):
pass

def getHostname(self):
return "mustard"

def getType(self):
return "QEMU"

def numOfDomains(self):
return 0

def listDomainsID(self):
return []

def listDefinedDomains(self):
return []

def getInfo(self):
return [arch.X86_64, 123456, 2, 2000,
2, 1, 1, 1]

self.conn = FakeConn()
self.stubs.Set(host.Host,
'get_connection',
lambda h: self.conn)
self.useFixture(fakelibvirt.FakeLibvirtFixture())

sys_meta = {
'instance_type_memory_mb': 2048,
Expand Down Expand Up @@ -710,54 +643,36 @@ def test_set_host_enabled_swallows_exceptions(self):
db_mock.side_effect = exception.NovaException
conn._set_host_enabled(False)

def test_prepare_pci_device(self):
@mock.patch.object(fakelibvirt.virConnect, "nodeDeviceLookupByName")
def test_prepare_pci_device(self, mock_lookup):

pci_devices = [dict(hypervisor_name='xxx')]

self.flags(virt_type='xen', group='libvirt')

conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)

class FakeDev(object):
def attach(self):
pass

def dettach(self):
pass

def reset(self):
pass
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
conn = drvr._host.get_connection()

self.mox.StubOutWithMock(self.conn, 'nodeDeviceLookupByName')
self.conn.nodeDeviceLookupByName('xxx').AndReturn(FakeDev())
self.conn.nodeDeviceLookupByName('xxx').AndReturn(FakeDev())
self.mox.ReplayAll()
conn._prepare_pci_devices_for_use(pci_devices)
mock_lookup.side_effect = lambda x: fakelibvirt.NodeDevice(conn)
drvr._prepare_pci_devices_for_use(pci_devices)

def test_prepare_pci_device_exception(self):
@mock.patch.object(fakelibvirt.virConnect, "nodeDeviceLookupByName")
@mock.patch.object(fakelibvirt.virNodeDevice, "dettach")
def test_prepare_pci_device_exception(self, mock_detach, mock_lookup):

pci_devices = [dict(hypervisor_name='xxx',
id='id1',
instance_uuid='uuid')]

self.flags(virt_type='xen', group='libvirt')
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)

class FakeDev(object):

def attach(self):
pass

def dettach(self):
raise libvirt.libvirtError("xxxxx")
drvr = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
conn = drvr._host.get_connection()

def reset(self):
pass
mock_lookup.side_effect = lambda x: fakelibvirt.NodeDevice(conn)
mock_detach.side_effect = libvirt.libvirtError("xxxx")

self.stubs.Set(self.conn, 'nodeDeviceLookupByName',
lambda x: FakeDev())
self.assertRaises(exception.PciDevicePrepareFailed,
conn._prepare_pci_devices_for_use, pci_devices)
drvr._prepare_pci_devices_for_use, pci_devices)

def test_detach_pci_devices_exception(self):

Expand Down Expand Up @@ -3724,12 +3639,6 @@ def test_get_guest_cpu_config_default_kvm(self, mock_flavor):
cpu_mode=None,
group='libvirt')

def get_lib_version_stub():
return (0 * 1000 * 1000) + (9 * 1000) + 11

self.stubs.Set(self.conn,
"getLibVersion",
get_lib_version_stub)
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), True)
instance_ref = objects.Instance(**self.test_instance)
flavor = instance_ref.get_flavor()
Expand Down Expand Up @@ -5065,17 +4974,16 @@ def test_attach_blockio_invalid_hypervisor(self):
instance,
"/dev/sda")

def test_attach_blockio_invalid_version(self):
def get_lib_version_stub():
return (0 * 1000 * 1000) + (9 * 1000) + 8
@mock.patch.object(fakelibvirt.virConnect, "getLibVersion")
def test_attach_blockio_invalid_version(self, mock_version):
mock_version.return_value = (0 * 1000 * 1000) + (9 * 1000) + 8
self.flags(virt_type='qemu', group='libvirt')
self.create_fake_libvirt_mock()
libvirt_driver.LibvirtDriver._conn.lookupByName = self.fake_lookup
instance = fake_instance.fake_instance_obj(
self.context, **self.test_instance)
self.mox.ReplayAll()
conn = libvirt_driver.LibvirtDriver(fake.FakeVirtAPI(), False)
self.stubs.Set(self.conn, "getLibVersion", get_lib_version_stub)
self.assertRaises(exception.Invalid,
conn.attach_volume, None,
{"driver_volume_type": "fake",
Expand Down

0 comments on commit 4b9bec3

Please sign in to comment.