tests: Convert to use pytest style 'assert'

Signed-off-by: Cole Robinson <crobinso@redhat.com>
This commit is contained in:
Cole Robinson 2020-09-18 14:56:36 -04:00
parent 2d8c1c5ab9
commit 71ac3ee044
9 changed files with 226 additions and 231 deletions

View File

@ -30,14 +30,13 @@ class TestCapabilities(unittest.TestCase):
caps = self._buildCaps(filename)
for f in host_feature_list:
self.assertEqual(
f in [feat.name for feat in caps.host.cpu.features], True)
assert f in [feat.name for feat in caps.host.cpu.features]
self.assertEqual(caps.host.cpu.model, "core2duo")
self.assertEqual(caps.host.cpu.vendor, "Intel")
self.assertEqual(caps.host.cpu.topology.threads, 3)
self.assertEqual(caps.host.cpu.topology.cores, 5)
self.assertEqual(caps.host.cpu.topology.sockets, 7)
assert caps.host.cpu.model == "core2duo"
assert caps.host.cpu.vendor == "Intel"
assert caps.host.cpu.topology.threads == 3
assert caps.host.cpu.topology.cores == 5
assert caps.host.cpu.topology.sockets == 7
def testCapsUtilFuncs(self):
caps_with_kvm = self._buildCaps("test-qemu-with-kvm.xml")
@ -47,7 +46,7 @@ class TestCapabilities(unittest.TestCase):
def test_utils(caps, has_guests, is_kvm):
assert caps.has_install_options() == has_guests
if caps.guests:
self.assertEqual(caps.guests[0].is_kvm_available(), is_kvm)
assert caps.guests[0].is_kvm_available() == is_kvm
test_utils(caps_empty, False, False)
test_utils(caps_with_kvm, True, True)
@ -61,9 +60,9 @@ class TestCapabilities(unittest.TestCase):
def testCapsNuma(self):
cells = self._buildCaps("lxc.xml").host.topology.cells
self.assertEqual(len(cells), 1)
self.assertEqual(len(cells[0].cpus), 8)
self.assertEqual(cells[0].cpus[3].id, '3')
assert len(cells) == 1
assert len(cells[0].cpus) == 8
assert cells[0].cpus[3].id == '3'
##############################
@ -74,27 +73,26 @@ class TestCapabilities(unittest.TestCase):
xml = open(DATADIR + "/test-domcaps.xml").read()
caps = DomainCapabilities(utils.URIs.open_testdriver_cached(), xml)
self.assertEqual(caps.os.loader.supported, True)
self.assertEqual(caps.os.loader.get_values(),
["/foo/bar", "/tmp/my_path"])
self.assertEqual(caps.os.loader.enum_names(), ["type", "readonly"])
self.assertEqual(caps.os.loader.get_enum("type").get_values(),
["rom", "pflash"])
assert caps.os.loader.supported is True
assert caps.os.loader.get_values() == ["/foo/bar", "/tmp/my_path"]
assert caps.os.loader.enum_names() == ["type", "readonly"]
assert caps.os.loader.get_enum("type").get_values() == [
"rom", "pflash"]
def testDomainCapabilitiesx86(self):
xml = open(DATADIR + "/kvm-x86_64-domcaps.xml").read()
caps = DomainCapabilities(utils.URIs.open_testdriver_cached(), xml)
self.assertEqual(caps.machine, "pc-i440fx-2.1")
self.assertEqual(caps.arch, "x86_64")
self.assertEqual(caps.domain, "kvm")
self.assertEqual(caps.path, "/bin/qemu-system-x86_64")
assert caps.machine == "pc-i440fx-2.1"
assert caps.arch == "x86_64"
assert caps.domain == "kvm"
assert caps.path == "/bin/qemu-system-x86_64"
custom_mode = caps.cpu.get_mode("custom")
self.assertTrue(bool(custom_mode))
assert bool(custom_mode)
cpu_model = custom_mode.get_model("Opteron_G4")
self.assertTrue(bool(cpu_model))
self.assertTrue(cpu_model.usable)
assert bool(cpu_model)
assert cpu_model.usable
models = caps.get_cpu_models()
assert len(models) > 10

View File

@ -5,6 +5,8 @@ import os
import unittest
import unittest.mock
import pytest
from virtinst import cli
from virtinst import pollhelpers
from virtinst import StoragePool
@ -44,7 +46,7 @@ class TestConn(unittest.TestCase):
assert conn.is_privileged() == (os.getuid() == 0)
# Hit fakuuri validation error, for old style opts
with self.assertRaises(RuntimeError):
with pytest.raises(RuntimeError):
cli.getConnection(fakeuri + ",qemu")
@unittest.mock.patch.dict(os.environ,

View File

@ -8,6 +8,8 @@
import os.path
import unittest
import pytest
from virtinst import Guest
from virtinst import NodeDevice
from virtinst import DeviceHostdev
@ -48,70 +50,69 @@ class TestNodeDev(unittest.TestCase):
def testFunkyChars(self):
# Ensure parsing doesn't fail
dev = NodeDevice(self.conn, funky_chars_xml)
self.assertEqual(dev.name, "L3B2616")
self.assertEqual(dev.device_type, "LENOVO")
assert dev.name == "L3B2616"
assert dev.device_type == "LENOVO"
def testNetDevice(self):
devname = "net_00_1c_25_10_b1_e4"
dev = self._nodeDevFromName(devname)
self.assertEqual(dev.name, devname)
self.assertEqual(dev.parent, "pci_8086_1049")
self.assertEqual(dev.device_type, "net")
self.assertEqual(dev.interface, "eth0")
assert dev.name == devname
assert dev.parent == "pci_8086_1049"
assert dev.device_type == "net"
assert dev.interface == "eth0"
def testPCIDevice(self):
nodename = "pci_8086_10fb"
obj = self._nodeDevFromName(nodename)
self.assertEqual(obj.is_pci_sriov(), True)
assert obj.is_pci_sriov() is True
nodename = "pci_8086_2448"
obj = self._nodeDevFromName(nodename)
self.assertEqual(obj.is_pci_bridge(), True)
assert obj.is_pci_bridge() is True
def testUSBDevDevice(self):
devname = "usb_device_781_5151_2004453082054CA1BEEE"
dev = self._nodeDevFromName(devname)
self.assertEqual(dev.vendor_name, "SanDisk Corp.")
self.assertEqual(dev.product_name, "Cruzer Micro 256/512MB Flash Drive")
assert dev.vendor_name == "SanDisk Corp."
assert dev.product_name == "Cruzer Micro 256/512MB Flash Drive"
devname = "usb_device_1d6b_1_0000_00_1a_0"
dev = self._nodeDevFromName(devname)
self.assertTrue(dev.is_usb_linux_root_hub())
assert dev.is_usb_linux_root_hub() is True
def testSCSIDevice(self):
devname = "pci_8086_2829_scsi_host_scsi_device_lun0"
dev = self._nodeDevFromName(devname)
self.assertEqual(dev.host, "0")
self.assertEqual(dev.bus, "0")
self.assertEqual(dev.target, "0")
assert dev.host == "0"
assert dev.bus == "0"
assert dev.target == "0"
def testStorageDevice(self):
devname = "storage_serial_SATA_WDC_WD1600AAJS__WD_WCAP95119685"
dev = self._nodeDevFromName(devname)
self.assertEqual(dev.block, "/dev/sda")
self.assertEqual(dev.drive_type, "disk")
self.assertEqual(dev.media_available, None)
assert dev.block == "/dev/sda"
assert dev.drive_type == "disk"
assert dev.media_available is None
devname = "storage_model_DVDRAM_GSA_U1200N"
dev = self._nodeDevFromName(devname)
self.assertEqual(dev.media_label, "Fedora12_media")
self.assertEqual(dev.media_available, 1)
assert dev.media_label == "Fedora12_media"
assert dev.media_available == 1
def testSCSIBus(self):
devname = "pci_8086_2829_scsi_host_1"
dev = self._nodeDevFromName(devname)
self.assertEqual(dev.host, "2")
assert dev.host == "2"
def testDRMDevice(self):
devname = "drm_renderD129"
dev = self._nodeDevFromName(devname)
self.assertEqual(dev.devnodes[0].path, "/dev/dri/renderD129")
self.assertEqual(dev.devnodes[0].node_type, "dev")
self.assertEqual(dev.devnodes[1].path,
"/dev/dri/by-path/pci-0000:00:02.0-render")
self.assertEqual(dev.devnodes[1].node_type, "link")
self.assertEqual(dev.is_drm_render(), True)
self.assertTrue(dev.get_devnode("frob"))
assert dev.devnodes[0].path == "/dev/dri/renderD129"
assert dev.devnodes[0].node_type == "dev"
assert dev.devnodes[1].path == "/dev/dri/by-path/pci-0000:00:02.0-render"
assert dev.devnodes[1].node_type == "link"
assert dev.is_drm_render() is True
assert dev.get_devnode("frob")
# NodeDevice 2 Device XML tests
@ -138,5 +139,5 @@ class TestNodeDev(unittest.TestCase):
# This should exist, since usbbus is not a valid device to
# pass to a guest.
self.assertRaises(ValueError,
pytest.raises(ValueError,
self._testNode2DeviceCompare, nodename, devfile)

View File

@ -32,10 +32,10 @@ class TestOSDB(unittest.TestCase):
conn = utils.URIs.open_testdefault_cached()
guest = Guest(conn)
res = OSDB.lookup_os("generic").get_recommended_resources()
self.assertEqual(res.get_recommended_ram(guest.os.arch), None)
assert res.get_recommended_ram(guest.os.arch) is None
res = OSDB.lookup_os("fedora21").get_recommended_resources()
self.assertEqual(res.get_recommended_ncpus(guest.os.arch), 2)
assert res.get_recommended_ncpus(guest.os.arch) == 2
def test_urldetct_matching_distros(self):
# pylint: disable=protected-access
@ -80,7 +80,7 @@ class TestOSDB(unittest.TestCase):
assert str(e).endswith("URL location")
# Trigger an error path for code coverage
self.assertEqual(OSDB.guess_os_by_tree(utils.TESTDIR), None)
assert OSDB.guess_os_by_tree(utils.TESTDIR) is None
def test_kernel_url(self):
def _c(name):
@ -89,25 +89,25 @@ class TestOSDB(unittest.TestCase):
self.skipTest("osinfo-db doesn't have '%s'" % name)
return osobj.get_kernel_url_arg()
self.assertEqual(_c("rhel7-unknown"), "inst.repo")
self.assertEqual(_c("rhel6-unknown"), "method")
self.assertEqual(_c("fedora-rawhide"), "inst.repo")
self.assertEqual(_c("fedora20"), "inst.repo")
self.assertEqual(_c("generic"), None)
self.assertEqual(_c("win10"), None)
self.assertEqual(_c("sle15"), "install")
assert _c("rhel7-unknown") == "inst.repo"
assert _c("rhel6-unknown") == "method"
assert _c("fedora-rawhide") == "inst.repo"
assert _c("fedora20") == "inst.repo"
assert _c("generic") is None
assert _c("win10") is None
assert _c("sle15") == "install"
def test_related_to(self):
# pylint: disable=protected-access
win10 = OSDB.lookup_os("win10")
self.assertTrue(win10._is_related_to("winxp"))
self.assertTrue(win10._is_related_to("win10"))
self.assertTrue(win10._is_related_to("fedora26") is False)
assert win10._is_related_to("winxp") is True
assert win10._is_related_to("win10") is True
assert win10._is_related_to("fedora26") is False
def test_drivers(self):
win7 = OSDB.lookup_os("win7")
generic = OSDB.lookup_os("generic")
self.assertFalse(generic.supports_unattended_drivers("x86_64"))
self.assertTrue(win7.supports_unattended_drivers("x86_64"))
self.assertFalse(win7.supports_unattended_drivers("fakearch"))
self.assertTrue(win7.get_pre_installable_drivers_location("x86_64"))
assert generic.supports_unattended_drivers("x86_64") is False
assert win7.supports_unattended_drivers("x86_64") is True
assert win7.supports_unattended_drivers("fakearch") is False
assert win7.get_pre_installable_drivers_location("x86_64")

View File

@ -195,7 +195,7 @@ class TestStorage(unittest.TestCase):
def testMisc(self):
# Misc coverage testing
vol = StorageVolume(self.conn)
self.assertTrue(vol.is_size_conflict()[0] is False)
assert vol.is_size_conflict()[0] is False
fullconn = utils.URIs.open_testdriver_cached()
glusterpool = fullconn.storagePoolLookupByName("gluster-pool")
@ -203,21 +203,20 @@ class TestStorage(unittest.TestCase):
glustervol = StorageVolume(fullconn)
glustervol.pool = glusterpool
self.assertTrue(glustervol.supports_format() is True)
assert glustervol.supports_format() is True
diskvol = StorageVolume(fullconn)
diskvol.pool = diskpool
self.assertTrue(diskvol.supports_format() is False)
assert diskvol.supports_format() is False
glusterpool.destroy()
StoragePool.ensure_pool_is_running(glusterpool)
# Check pool collision detection
self.assertEqual(
StoragePool.find_free_name(fullconn, "gluster-pool"),
"gluster-pool-1")
name = StoragePool.find_free_name(fullconn, "gluster-pool")
assert name == "gluster-pool-1"
def testEnumerateLogical(self):
lst = StoragePool.pool_list_from_sources(self.conn,
StoragePool.TYPE_LOGICAL)
self.assertEqual(lst, ["testvg1", "testvg2"])
assert lst == ["testvg1", "testvg2"]

View File

@ -5,6 +5,8 @@
import unittest
import pytest
from virtinst import URI
import tests
@ -19,16 +21,16 @@ class TestURI(unittest.TestCase):
hostname='', query='', fragment='',
is_ipv6=False, host_is_ipv4_string=False):
uriinfo = URI(uri)
self.assertEqual(scheme, uriinfo.scheme)
self.assertEqual(transport, uriinfo.transport)
self.assertEqual(port, uriinfo.port)
self.assertEqual(username, uriinfo.username)
self.assertEqual(path, uriinfo.path)
self.assertEqual(hostname, uriinfo.hostname)
self.assertEqual(query, uriinfo.query)
self.assertEqual(fragment, uriinfo.fragment)
self.assertEqual(is_ipv6, uriinfo.is_ipv6)
self.assertEqual(host_is_ipv4_string, uriinfo.host_is_ipv4_string)
assert scheme == uriinfo.scheme
assert transport == uriinfo.transport
assert port == uriinfo.port
assert username == uriinfo.username
assert path == uriinfo.path
assert hostname == uriinfo.hostname
assert query == uriinfo.query
assert fragment == uriinfo.fragment
assert is_ipv6 == uriinfo.is_ipv6
assert host_is_ipv4_string == uriinfo.host_is_ipv4_string
def testURIs(self):
self._compare("lxc://", scheme="lxc")
@ -59,15 +61,14 @@ class TestURI(unittest.TestCase):
def test_magicuri_connver(self):
uri = tests.utils.URIs.test_default + ",connver=1,libver=2"
conn = tests.utils.URIs.openconn(uri)
self.assertEqual(conn.conn_version(), 1)
self.assertEqual(conn.local_libvirt_version(), 2)
assert conn.conn_version() == 1
assert conn.local_libvirt_version() == 2
conn = tests.utils.URIs.openconn("test:///default")
# Add some support tests with it
with self.assertRaises(ValueError) as cm:
with pytest.raises(ValueError,
match=".*type <class 'libvirt.virDomain'>.*"):
conn.support.domain_xml_inactive("foo")
self.assertTrue("must be of type <class 'libvirt.virDomain'>" in
str(cm.exception))
# pylint: disable=protected-access
from virtinst import support
@ -75,16 +76,16 @@ class TestURI(unittest.TestCase):
check = support._SupportCheck(**kwargs)
return check(conn)
self.assertFalse(_run(function="virNope.Foo"))
self.assertFalse(_run(function="virDomain.IDontExist"))
self.assertTrue(_run(function="virDomain.isActive"))
self.assertFalse(_run(function="virConnect.getVersion",
flag="SOME_FLAG_DOESNT_EXIST"))
self.assertFalse(_run(version="1000.0.0"))
self.assertFalse(_run(hv_version={"test": "1000.0.0"}))
self.assertFalse(_run(hv_libvirt_version={"test": "1000.0.0"}))
self.assertFalse(_run(hv_libvirt_version={"qemu": "1.2.3"}))
self.assertTrue(_run(hv_libvirt_version={"qemu": "1.2.3", "all": 0}))
assert _run(function="virNope.Foo") is False
assert _run(function="virDomain.IDontExist") is False
assert _run(function="virDomain.isActive") is True
assert _run(function="virConnect.getVersion",
flag="SOME_FLAG_DOESNT_EXIST") is False
assert _run(version="1000.0.0") is False
assert _run(hv_version={"test": "1000.0.0"}) is False
assert _run(hv_libvirt_version={"test": "1000.0.0"}) is False
assert _run(hv_libvirt_version={"qemu": "1.2.3"}) is False
assert _run(hv_libvirt_version={"qemu": "1.2.3", "all": 0}) is True
dom = conn.lookupByName("test")
self.assertTrue(conn.support.domain_xml_inactive(dom))
assert conn.support.domain_xml_inactive(dom) is True

View File

@ -8,6 +8,8 @@ import re
import sys
import unittest
import pytest
from tests import utils
import virtinst.progress
@ -193,20 +195,18 @@ class URLTests(unittest.TestCase):
def test001BadURL(self):
badurl = "http://aksdkakskdfa-idontexist.com/foo/tree"
with self.assertRaises(ValueError) as cm:
with pytest.raises(ValueError, match=".*maybe you mistyped.*"):
installer = Installer(hvmguest.conn, location=badurl)
installer.detect_distro(hvmguest)
self.assertTrue("maybe you mistyped" in str(cm.exception))
# Non-existent cdrom fails
with self.assertRaises(ValueError) as cm:
with pytest.raises(ValueError, match=".*non-existent path.*"):
installer = Installer(hvmguest.conn, cdrom="/not/exist/foobar")
self.assertEqual(None, installer.detect_distro(hvmguest))
self.assertTrue("non-existent path" in str(cm.exception))
assert installer.detect_distro(hvmguest) is None
# Ensure existing but non-distro file doesn't error
installer = Installer(hvmguest.conn, cdrom="/dev/null")
self.assertEqual(None, installer.detect_distro(hvmguest))
assert installer.detect_distro(hvmguest) is None
def _make_tests():

View File

@ -86,35 +86,33 @@ class TestXMLMisc(unittest.TestCase):
#
# Note: using single quotes in strings to avoid
# codespell flagging the 'ba' assert
self.assertEqual('a', DeviceDisk.num_to_target(1))
self.assertEqual('b', DeviceDisk.num_to_target(2))
self.assertEqual('z', DeviceDisk.num_to_target(26))
self.assertEqual('aa', DeviceDisk.num_to_target(27))
self.assertEqual('ab', DeviceDisk.num_to_target(28))
self.assertEqual('az', DeviceDisk.num_to_target(52))
self.assertEqual('ba', DeviceDisk.num_to_target(53))
self.assertEqual('zz', DeviceDisk.num_to_target(27 * 26))
self.assertEqual('aaa', DeviceDisk.num_to_target(27 * 26 + 1))
assert DeviceDisk.num_to_target(1) == 'a'
assert DeviceDisk.num_to_target(2) == 'b'
assert DeviceDisk.num_to_target(26) == 'z'
assert DeviceDisk.num_to_target(27) == 'aa'
assert DeviceDisk.num_to_target(28) == 'ab'
assert DeviceDisk.num_to_target(52) == 'az'
assert DeviceDisk.num_to_target(53) == 'ba'
assert DeviceDisk.num_to_target(27 * 26) == 'zz'
assert DeviceDisk.num_to_target(27 * 26 + 1) == 'aaa'
self.assertEqual(DeviceDisk.target_to_num('hda'), 0)
self.assertEqual(DeviceDisk.target_to_num('hdb'), 1)
self.assertEqual(DeviceDisk.target_to_num('sdz'), 25)
self.assertEqual(DeviceDisk.target_to_num('sdaa'), 26)
self.assertEqual(DeviceDisk.target_to_num('vdab'), 27)
self.assertEqual(DeviceDisk.target_to_num('vdaz'), 51)
self.assertEqual(DeviceDisk.target_to_num('xvdba'), 52)
self.assertEqual(DeviceDisk.target_to_num('xvdzz'),
26 * (25 + 1) + 25)
self.assertEqual(DeviceDisk.target_to_num('xvdaaa'),
26 * 26 * 1 + 26 * 1 + 0)
assert DeviceDisk.target_to_num('hda') == 0
assert DeviceDisk.target_to_num('hdb') == 1
assert DeviceDisk.target_to_num('sdz') == 25
assert DeviceDisk.target_to_num('sdaa') == 26
assert DeviceDisk.target_to_num('vdab') == 27
assert DeviceDisk.target_to_num('vdaz') == 51
assert DeviceDisk.target_to_num('xvdba') == 52
assert DeviceDisk.target_to_num('xvdzz') == 26 * (25 + 1) + 25
assert DeviceDisk.target_to_num('xvdaaa') == 26 * 26 * 1 + 26 * 1 + 0
disk = virtinst.DeviceDisk(self.conn)
disk.bus = 'ide'
self.assertEqual('hda', disk.generate_target([]))
self.assertEqual('hdb', disk.generate_target(['hda']))
self.assertEqual('hdc', disk.generate_target(['hdb', 'sda']))
self.assertEqual('hdb', disk.generate_target(['hda', 'hdd']))
assert disk.generate_target([]) == 'hda'
assert disk.generate_target(['hda']) == 'hdb'
assert disk.generate_target(['hdb', 'sda']) == 'hdc'
assert disk.generate_target(['hda', 'hdd']) == 'hdb'
def testQuickTreeinfo(self):
# Simple sanity test to make sure detect_distro works. test-urls
@ -123,13 +121,13 @@ class TestXMLMisc(unittest.TestCase):
location=utils.DATADIR + "/fakemedia/fakefedoratree")
g = _make_guest()
v = i.detect_distro(g)
self.assertEqual(v, "fedora17")
assert v == "fedora17"
i = _make_installer(
location=utils.DATADIR + "/fakemedia/fakerhel6tree")
g = _make_guest()
v = i.detect_distro(g)
self.assertEqual(v, "rhel6.0")
assert v == "rhel6.0"
def testCDROMInsert(self):
# After set_install_defaults, cdrom media should be inserted
@ -151,25 +149,25 @@ class TestXMLMisc(unittest.TestCase):
cpu.set_topology_defaults(6)
def get_top(_c):
return [_c.topology.sockets, _c.topology.cores, _c.topology.threads]
self.assertEqual(get_top(cpu), [2, 3, 1])
assert get_top(cpu) == [2, 3, 1]
cpu = virtinst.DomainCpu(self.conn)
cpu.topology.cores = "4"
cpu.set_topology_defaults(9)
self.assertEqual(get_top(cpu), [2, 4, 1])
assert get_top(cpu) == [2, 4, 1]
cpu = virtinst.DomainCpu(self.conn)
cpu.topology.threads = "3"
cpu.set_topology_defaults(14)
self.assertEqual(get_top(cpu), [4, 1, 3])
assert get_top(cpu) == [4, 1, 3]
cpu = virtinst.DomainCpu(self.conn)
cpu.topology.sockets = 5
cpu.topology.cores = 2
self.assertEqual(cpu.vcpus_from_topology(), 10)
assert cpu.vcpus_from_topology() == 10
cpu = virtinst.DomainCpu(self.conn)
self.assertEqual(cpu.vcpus_from_topology(), 1)
assert cpu.vcpus_from_topology() == 1
def test_set_defaults_double(self):
"""
@ -181,21 +179,21 @@ class TestXMLMisc(unittest.TestCase):
xml1 = g.get_xml()
g.set_defaults(None)
xml2 = g.get_xml()
self.assertEqual(xml1, xml2)
assert xml1 == xml2
def test_guest_osinfo_metadata(self):
g = _make_guest()
self.assertEqual(g.osinfo.name, "generic")
assert g.osinfo.name == "generic"
g.set_os_name("fedora17")
self.assertEqual(g.osinfo.name, "fedora17")
assert g.osinfo.name == "fedora17"
g = _make_guest()
g._metadata.libosinfo.os_id = "http://fedoraproject.org/fedora/20" # pylint: disable=protected-access
self.assertEqual(g.osinfo.name, "fedora20")
assert g.osinfo.name == "fedora20"
g = _make_guest()
g._metadata.libosinfo.os_id = "http://example.com/idontexit" # pylint: disable=protected-access
self.assertEqual(g.osinfo.name, "generic")
assert g.osinfo.name == "generic"
def test_dir_searchable(self):
# Normally the dir searchable test is skipped in the unittest,
@ -216,22 +214,22 @@ class TestXMLMisc(unittest.TestCase):
# Invalid uid
_set_caps_baselabel_uid(-1)
searchdata = virtinst.DeviceDisk.check_path_search(conn, tmpdir)
self.assertEqual(searchdata.uid, None)
assert searchdata.uid is None
# Use our uid, verify it shows we have expected access
_set_caps_baselabel_uid(os.getuid())
searchdata = virtinst.DeviceDisk.check_path_search(conn,
tmpdir + "/footest")
self.assertEqual(searchdata.uid, os.getuid())
self.assertEqual(searchdata.fixlist, [])
assert searchdata.uid == os.getuid()
assert searchdata.fixlist == []
# Remove perms on the tmpdir, now it should report failures
os.chmod(tmpdir, 0o000)
searchdata = virtinst.DeviceDisk.check_path_search(conn, tmpdir)
self.assertEqual(searchdata.fixlist, [tmpdir])
assert searchdata.fixlist == [tmpdir]
errdict = virtinst.DeviceDisk.fix_path_search(searchdata)
self.assertTrue(not bool(errdict))
assert not bool(errdict)
# Mock setfacl to definitely fail
with unittest.mock.patch("virtinst.diskbackend.SETFACL",
@ -259,15 +257,15 @@ class TestXMLMisc(unittest.TestCase):
testuuid = virtinst.Guest.generate_uuid(self.conn)
randomuuid = virtinst.Guest.generate_uuid(testconn)
self.assertTrue(randomuuid != testuuid)
self.assertTrue(len(randomuuid) == len(testuuid))
assert randomuuid != testuuid
assert len(randomuuid) == len(testuuid)
testmac = virtinst.DeviceInterface.generate_mac(self.conn)
randommac = virtinst.DeviceInterface.generate_mac(testconn)
qemumac = virtinst.DeviceInterface.generate_mac(kvmconn)
self.assertTrue(randommac != testmac)
self.assertTrue(qemumac != testmac)
self.assertTrue(len(randommac) == len(testmac))
assert randommac != testmac
assert qemumac != testmac
assert len(randommac) == len(testmac)
# Ensure check_mac_in_use doesn't error on None
virtinst.DeviceInterface.check_mac_in_use(self.conn, None)

View File

@ -7,6 +7,8 @@ import glob
import traceback
import unittest
import pytest
import virtinst
from tests import utils
@ -70,12 +72,12 @@ class XMLParseTest(unittest.TestCase):
set newval, and make sure it is returned properly
"""
curval = virtinst.xmlutil.get_prop_path(obj, param)
self.assertEqual(initval, curval)
assert initval == curval
for newval in args:
virtinst.xmlutil.set_prop_path(obj, param, newval)
curval = virtinst.xmlutil.get_prop_path(obj, param)
self.assertEqual(newval, curval)
assert newval == curval
def _make_checker(self, obj):
def check(name, initval, *args):
@ -135,10 +137,10 @@ class XMLParseTest(unittest.TestCase):
check("os_id", "http://fedoraproject.org/fedora/17")
guest.set_os_name("fedora10")
check("os_id", "http://fedoraproject.org/fedora/10")
self.assertEqual(guest.osinfo.name, "fedora10")
assert guest.osinfo.name == "fedora10"
guest.set_os_name("generic")
check("os_id", None, "frib")
self.assertEqual(guest.osinfo.name, "generic")
assert guest.osinfo.name == "generic"
check = self._make_checker(guest.clock)
check("offset", "utc", "localtime")
@ -169,8 +171,7 @@ class XMLParseTest(unittest.TestCase):
check("kernel_args", None)
guest.os.set_initargs_string("foo 'bar baz' frib")
self.assertEqual([i.val for i in guest.os.initargs],
["foo", "bar baz", "frib"])
assert [i.val for i in guest.os.initargs] == ["foo", "bar baz", "frib"]
check = self._make_checker(guest.features)
check("acpi", True, False)
@ -205,8 +206,7 @@ class XMLParseTest(unittest.TestCase):
check("policy", "force", "disable")
rmfeat = guest.cpu.features[3]
guest.cpu.remove_child(rmfeat)
self.assertEqual(rmfeat.get_xml(),
"""<feature name="foo" policy="bar"/>\n""")
assert rmfeat.get_xml() == """<feature name="foo" policy="bar"/>\n"""
guest.cpu.add_feature("addfeature")
check = self._make_checker(guest.numatune)
@ -272,20 +272,18 @@ class XMLParseTest(unittest.TestCase):
check = self._make_checker(guest.features)
check("acpi", False, True)
check("pae", False)
self.assertTrue(
guest.features.get_xml().startswith("<features"))
assert guest.features.get_xml().startswith("<features")
check = self._make_checker(guest.clock)
check("offset", None, "utc")
self.assertTrue(guest.clock.get_xml().startswith("<clock"))
assert guest.clock.get_xml().startswith("<clock") is True
seclabel = virtinst.DomainSeclabel(guest.conn)
guest.add_child(seclabel)
seclabel.model = "testSecurity"
seclabel.type = "static"
seclabel.label = "frob"
self.assertTrue(
guest.seclabels[0].get_xml().startswith("<seclabel"))
assert guest.seclabels[0].get_xml().startswith("<seclabel")
check = self._make_checker(guest.cpu)
check("model", None)
@ -295,13 +293,13 @@ class XMLParseTest(unittest.TestCase):
check("topology.cores", None, 4)
guest.cpu.add_feature("x2apic", "forbid")
guest.cpu.set_topology_defaults(guest.vcpus)
self.assertTrue(guest.cpu.get_xml().startswith("<cpu"))
self.assertEqual(guest.cpu.get_xml_id(), "./cpu")
self.assertEqual(guest.cpu.get_xml_idx(), 0)
self.assertEqual(guest.get_xml_id(), ".")
self.assertEqual(guest.get_xml_idx(), 0)
assert guest.cpu.get_xml().startswith("<cpu") is True
assert guest.cpu.get_xml_id() == "./cpu"
assert guest.cpu.get_xml_idx() == 0
assert guest.get_xml_id() == "."
assert guest.get_xml_idx() == 0
self.assertTrue(guest.os.get_xml().startswith("<os"))
assert guest.os.get_xml().startswith("<os") is True
self._alter_compare(guest.get_xml(), outfile)
@ -495,40 +493,40 @@ class XMLParseTest(unittest.TestCase):
iface_2 = guest.devices.interface[1]
redirdev_1 = guest.devices.redirdev[0]
self.assertEqual(guest.os.bootorder, ['hd'])
self.assertEqual(disk_1.boot.order, None)
self.assertEqual(disk_2.boot.order, 10)
self.assertEqual(disk_3.boot.order, 10)
self.assertEqual(disk_4.boot.order, 1)
self.assertEqual(iface_1.boot.order, 2)
self.assertEqual(iface_2.boot.order, None)
self.assertEqual(redirdev_1.boot.order, 3)
assert guest.os.bootorder == ['hd']
assert disk_1.boot.order is None
assert disk_2.boot.order == 10
assert disk_3.boot.order == 10
assert disk_4.boot.order == 1
assert iface_1.boot.order == 2
assert iface_2.boot.order is None
assert redirdev_1.boot.order == 3
guest.reorder_boot_order(disk_1, 1)
self.assertEqual(guest.os.bootorder, [])
self.assertEqual(disk_1.boot.order, 1)
self.assertEqual(disk_2.boot.order, 10)
self.assertEqual(disk_3.boot.order, 10)
assert guest.os.bootorder == []
assert disk_1.boot.order == 1
assert disk_2.boot.order == 10
assert disk_3.boot.order == 10
# verify that the used algorithm preserves the order of
# records with equal boot indices
self.assertIs(disk_2, guest.devices.disk[1])
self.assertIs(disk_3, guest.devices.disk[2])
self.assertEqual(disk_4.boot.order, 2)
self.assertEqual(iface_1.boot.order, 3)
self.assertEqual(iface_2.boot.order, None)
self.assertEqual(redirdev_1.boot.order, 4)
assert disk_2 is guest.devices.disk[1]
assert disk_3 is guest.devices.disk[2]
assert disk_4.boot.order == 2
assert iface_1.boot.order == 3
assert iface_2.boot.order is None
assert redirdev_1.boot.order == 4
try:
self._alter_compare(guest.get_xml(), outfile)
except RuntimeError as error:
self.assertIn("unsupported configuration", str(error))
assert "unsupported configuration" in str(error)
guest.reorder_boot_order(disk_2, 10)
self.assertEqual(disk_2.boot.order, 10)
self.assertEqual(disk_3.boot.order, 11)
self.assertIs(disk_2, guest.devices.disk[1])
self.assertIs(disk_3, guest.devices.disk[2])
assert disk_2.boot.order == 10
assert disk_3.boot.order == 11
assert disk_2 is guest.devices.disk[1]
assert disk_3 is guest.devices.disk[2]
outfile = self._gen_outfile_path("change-devices-bootorder-fixed")
self._alter_compare(guest.get_xml(), outfile)
@ -538,7 +536,7 @@ class XMLParseTest(unittest.TestCase):
"""<target dev="hda" bus="ide"/></disk>\n""")
d = virtinst.DeviceDisk(self.conn, parsexml=xml)
self._set_and_check(d, "target", "hda", "hdb")
self.assertEqual(xml.replace("hda", "hdb"), d.get_xml())
assert xml.replace("hda", "hdb") == d.get_xml()
def testAlterChars(self):
guest, outfile = self._get_test_content("change-chars")
@ -604,8 +602,8 @@ class XMLParseTest(unittest.TestCase):
check("source.channel", "org.spice-space.webdav.0", "test.1")
check("target_type", "virtio")
check("target_name", "org.spice-space.webdav.0", "test.2")
self.assertEqual(channel3.get_xml_id(), "./devices/channel[3]")
self.assertEqual(channel3.get_xml_idx(), 2)
assert channel3.get_xml_id() == "./devices/channel[3]"
assert channel3.get_xml_idx() == 2
self._alter_compare(guest.get_xml(), outfile)
@ -972,7 +970,7 @@ class XMLParseTest(unittest.TestCase):
check = self._make_checker(dev2.address)
dev2.address.domain = "0x0010"
self.assertEqual(dev2.address.domain, 16)
assert dev2.address.domain == 16
check("type", "pci")
check("domain", 16, 1)
check("bus", 0, 4)
@ -1111,8 +1109,8 @@ class XMLParseTest(unittest.TestCase):
guest.xmlns_qemu.args.add_new().value = "additional-arg"
arg0 = guest.xmlns_qemu.args[0]
guest.xmlns_qemu.remove_child(guest.xmlns_qemu.args[0])
self.assertEqual(arg0.get_xml(),
"<qemu:arg xmlns:qemu=\"http://libvirt.org/schemas/domain/qemu/1.0\" value=\"-somenewarg\"/>\n")
x = "<qemu:arg xmlns:qemu=\"http://libvirt.org/schemas/domain/qemu/1.0\" value=\"-somenewarg\"/>\n"
assert arg0.get_xml() == x
check = self._make_checker(guest.xmlns_qemu.envs[0])
check("name", "SOMEENV")
@ -1188,8 +1186,8 @@ class XMLParseTest(unittest.TestCase):
def testGuestBootorder(self):
guest, outfile = self._get_test_content("bootorder", kvm=True)
self.assertEqual(guest.get_boot_order(), ['./devices/disk[1]'])
self.assertEqual(guest.get_boot_order(legacy=True), ['hd'])
assert guest.get_boot_order() == ['./devices/disk[1]']
assert guest.get_boot_order(legacy=True) == ['hd']
legacy_order = ['hd', 'fd', 'cdrom', 'network']
dev_order = ['./devices/disk[1]',
@ -1197,12 +1195,12 @@ class XMLParseTest(unittest.TestCase):
'./devices/disk[2]',
'./devices/interface[1]']
guest.set_boot_order(legacy_order, legacy=True)
self.assertEqual(guest.get_boot_order(), dev_order)
self.assertEqual(guest.get_boot_order(legacy=True), legacy_order)
assert guest.get_boot_order() == dev_order
assert guest.get_boot_order(legacy=True) == legacy_order
guest.set_boot_order(dev_order)
self.assertEqual(guest.get_boot_order(), dev_order)
self.assertEqual(guest.get_boot_order(legacy=True), [])
assert guest.get_boot_order() == dev_order
assert guest.get_boot_order(legacy=True) == []
self._alter_compare(guest.get_xml(), outfile)
@ -1372,25 +1370,25 @@ class XMLParseTest(unittest.TestCase):
check("macaddr", None, "52:54:00:69:eb:FF")
check("virtualport_type", None, "openvswitch")
self.assertEqual(len(net.portgroups), 2)
assert len(net.portgroups) == 2
check = self._make_checker(net.portgroups[0])
check("name", "engineering", "foo")
check("default", True, False)
self.assertEqual(len(net.ips), 4)
assert len(net.ips) == 4
check = self._make_checker(net.ips[0])
check("address", "192.168.7.1", "192.168.8.1")
check("netmask", "255.255.255.0", "255.255.254.0")
self.assertEqual(net.can_pxe(), False)
assert net.can_pxe() is False
check("tftp", None, "/var/lib/tftproot")
check("bootp_file", None, "pxeboot.img")
check("bootp_server", None, "1.2.3.4")
self.assertEqual(net.can_pxe(), True)
assert net.can_pxe() is True
check = self._make_checker(net.forward)
check("mode", "nat", "route")
check("dev", None, "eth22")
self.assertEqual(net.can_pxe(), True)
assert net.can_pxe() is True
check = self._make_checker(net.ips[0].ranges[0])
check("start", "192.168.7.128", "192.168.8.128")
@ -1430,7 +1428,7 @@ class XMLParseTest(unittest.TestCase):
check("mode", "open")
check("dev", None)
self.assertEqual(len(net.ips), 1)
assert len(net.ips) == 1
check = self._make_checker(net.ips[0])
check("address", "192.168.100.1", "192.168.101.1")
check("netmask", "255.255.255.0", "255.255.254.0")
@ -1493,37 +1491,35 @@ class XMLParseTest(unittest.TestCase):
" <source><address bus='hello'/></source>\n</hostdev>")
dev = virtinst.DeviceHostdev(self.conn, parsexml=xml)
self.assertEqual(dev.managed, "foo")
self.assertEqual(dev.rom_bar, "wibble")
self.assertEqual(dev.scsi_bus, "hello")
assert dev.managed == "foo"
assert dev.rom_bar == "wibble"
assert dev.scsi_bus == "hello"
dev.managed = "test1"
dev.rom_bar = "test2"
self.assertEqual(dev.managed, "test1")
self.assertEqual(dev.rom_bar, "test2")
assert dev.managed == "test1"
assert dev.rom_bar == "test2"
with self.assertRaises(ValueError):
with pytest.raises(ValueError):
dev.scsi_bus = "goodbye"
def testXMLCoverage(self):
with self.assertRaises(RuntimeError) as cm:
with pytest.raises(RuntimeError, match=".*'foo'.*"):
# Ensure we validate root element
virtinst.DeviceDisk(self.conn, parsexml="<foo/>")
self.assertTrue("'foo'" in str(cm.exception))
with self.assertRaises(Exception) as cm:
with pytest.raises(Exception, match=".*xmlParseDoc.*"):
# Ensure we validate root element
virtinst.DeviceDisk(self.conn, parsexml=-1)
self.assertTrue("xmlParseDoc" in str(cm.exception))
from virtinst import xmlutil
with self.assertRaises(xmlutil.DevError):
with pytest.raises(xmlutil.DevError):
raise xmlutil.DevError("for coverage")
with self.assertRaises(ValueError):
with pytest.raises(ValueError):
virtinst.DeviceDisk.validate_generic_name("objtype", None)
with self.assertRaises(ValueError):
with pytest.raises(ValueError):
virtinst.DeviceDisk.validate_generic_name("objtype", "foo bar")
# Test property __repr__ for code coverage
@ -1568,7 +1564,7 @@ class XMLParseTest(unittest.TestCase):
disk.validate()
disk.is_size_conflict()
disk.build_storage(None)
self.assertTrue(getattr(disk, "_storage_backend").is_stub())
assert getattr(disk, "_storage_backend").is_stub() is True
# Stub backend coverage testing
backend = getattr(disk, "_storage_backend")
@ -1582,9 +1578,9 @@ class XMLParseTest(unittest.TestCase):
assert backend.get_parent_pool() is None
disk.set_backend_for_existing_path()
self.assertFalse(getattr(disk, "_storage_backend").is_stub())
assert getattr(disk, "_storage_backend").is_stub() is False
with self.assertRaises(ValueError):
with pytest.raises(ValueError):
disk.validate()
# Ensure set_backend_for_existing_path resolves a path