def test_upgrade_volatile_running_config(self): with namedTemporaryDir() as pdir, namedTemporaryDir() as vdir: with mock.patch.object(netconf, 'CONF_RUN_DIR', pdir),\ mock.patch.object(netconf, 'CONF_VOLATILE_RUN_DIR', vdir): vol_rconfig = netconf.RunningConfig(volatile=True) vol_rconfig.save() netupgrade.upgrade() pers_rconfig = netconf.RunningConfig() self.assertFalse(vol_rconfig.config_exists()) self.assertTrue(pers_rconfig.config_exists())
def _commonConvertExternalVM(self, url): with namedTemporaryDir() as v2v._V2V_DIR, \ namedTemporaryDir() as v2v._LOG_DIR: v2v.convert_external_vm(url, 'root', ProtectedPassword('mypassword'), self.vminfo, self.job_id, FakeIRS()) job = v2v._jobs[self.job_id] job.wait() self.assertEqual(job.status, v2v.STATUS.DONE)
def test_full(self): with namedTemporaryDir() as tmpdir: filename = os.path.join(tmpdir, 'test') with io.open(filename, "wb") as f: f.write(b"x" * qcow2.CLUSTER_SIZE * 3) runs = qemuimg.map(filename) self.assertEqual(qcow2.count_clusters(runs), 3)
def test_empty_sparse(self): with namedTemporaryDir() as tmpdir: filename = os.path.join(tmpdir, 'test') with io.open(filename, "wb") as f: f.truncate(MB) runs = qemuimg.map(filename) self.assertEqual(qcow2.count_clusters(runs), 0)
def check_best_small(self, compat, size): with namedTemporaryDir() as tmpdir: filename = os.path.join(tmpdir, 'test') with io.open(filename, "wb") as f: f.truncate(size) f.write("x" * MB) self.check_estimate(filename, compat)
def test_check(self): with namedTemporaryDir() as tmpdir: path = os.path.join(tmpdir, 'test.qcow2') qemuimg.create(path, size=1048576, format=qemuimg.FORMAT.QCOW2) info = qemuimg.check(path) # The exact value depends on qcow2 internals self.assertEqual(int, type(info['offset']))
def test_one_block(self, offset, length, expected_length, qcow2_compat): with namedTemporaryDir() as tmpdir: size = 1048576 image = os.path.join(tmpdir, "base.img") qemuimg.create(image, size=size, format=self.FORMAT, qcow2Compat=qcow2_compat) qemu_pattern_write(image, self.FORMAT, offset=offset, len=length, pattern=0xf0) expected = [ # run 1 - empty { "start": 0, "length": offset, "data": False, "zero": True, }, # run 2 - data { "start": offset, "length": expected_length, "data": True, "zero": False, }, # run 3 - empty { "start": offset + expected_length, "length": size - offset - expected_length, "data": False, "zero": True, }, ] self.check_map(qemuimg.map(image), expected)
def test_getmetaparam(self): with namedTemporaryDir() as tmpdir: metadata = {sd.DMDK_VERSION: 3} manifest = make_filesd_manifest(tmpdir, metadata) metadata[sd.DMDK_SDUUID] = manifest.sdUUID self.assertEquals(manifest.sdUUID, manifest.getMetaParam(sd.DMDK_SDUUID))
def testLoopMount(self): with namedTemporaryDir() as mpath: # two nested with blocks to be python 2.6 friendly with createFloppyImage(FLOPPY_SIZE) as path: m = mount.Mount(path, mpath) with loop_mount(m): self.assertTrue(m.isMounted())
def testFullDir(self, persist=False): """ Test that rotator does it's basic functionality. """ # Prepare prefix = "prefix" stubContent = ('"Multiple exclamation marks", ' 'he went on, shaking his head, ' '"are a sure sign of a diseased mind."') # (C) Terry Pratchet - Small Gods with namedTemporaryDir() as dir: gen = 10 expectedDirContent = [] for i in range(gen): fname = "%s.txt.%d" % (prefix, i + 1) expectedDirContent.append("%s.txt.%d" % (prefix, i + 1)) f = open(os.path.join(dir, fname), "wb") f.write(stubContent) f.flush() f.close() # Rotate misc.rotateFiles(dir, prefix, gen, persist=persist) # Test result currentDirContent = os.listdir(dir) expectedDirContent.sort() currentDirContent.sort() self.assertEquals(currentDirContent, expectedDirContent)
def test_getblocksize_defaults(self): with namedTemporaryDir() as tmpdir: lvm = FakeLVM(tmpdir) with MonkeyPatchScope([(blockSD, 'lvm', lvm)]): manifest = make_blocksd(tmpdir, lvm) self.assertEquals(512, manifest.logBlkSize) self.assertEquals(512, manifest.phyBlkSize)
def test_lvpath(self): with namedTemporaryDir() as tmpdir: lvm = FakeLVM(tmpdir) vg_name = 'foo' lv_name = 'bar' expected = os.path.join(tmpdir, 'dev', vg_name, lv_name) self.assertEqual(expected, lvm.lvPath(vg_name, lv_name))
def _setup_test_modules(self, files): with namedTemporaryDir() as path: for f in files: fileutils.touch_file(os.path.join(path, f)) fileutils.touch_file(os.path.join(path, '__init__.py')) sys.path.insert(0, os.path.dirname(path)) yield importlib.import_module(os.path.basename(path))
def VM(params=None, devices=None, runCpu=False, arch=cpuarch.X86_64, status=None, cif=None, create_device_objects=False, post_copy=None, recover=False): with namedTemporaryDir() as tmpDir: with MonkeyPatchScope([(constants, 'P_VDSM_RUN', tmpDir), (libvirtconnection, 'get', Connection), (containersconnection, 'get', Connection), (vm.Vm, '_updateDomainDescriptor', _updateDomainDescriptor), (vm.Vm, 'send_status_event', lambda _, **kwargs: None)]): vmParams = {'vmId': 'TESTING', 'vmName': 'nTESTING'} vmParams.update({} if params is None else params) cif = ClientIF() if cif is None else cif fake = vm.Vm(cif, vmParams, recover=recover) cif.vmContainer[fake.id] = fake fake.arch = arch fake.guestAgent = GuestAgent() fake.conf['devices'] = [] if devices is None else devices if create_device_objects: fake._devices = common.dev_map_from_dev_spec_map( fake._devSpecMapFromConf(), fake.log ) fake._guestCpuRunning = runCpu if status is not None: fake._lastStatus = status if post_copy is not None: fake._post_copy = post_copy sampling.stats_cache.add(fake.id) yield fake
def testEmptyDir(self, persist=False): """ Test that when given an empty dir the rotator works correctly. """ prefix = "prefix" with namedTemporaryDir() as dir: misc.rotateFiles(dir, prefix, 0, persist=persist)
def test_getblocksize(self): with namedTemporaryDir(): metadata = {blockSD.DMDK_LOGBLKSIZE: 2048, blockSD.DMDK_PHYBLKSIZE: 1024} manifest = self.make_manifest(metadata) self.assertEquals(2048, manifest.logBlkSize) self.assertEquals(1024, manifest.phyBlkSize)
def test_getmetaparam(self): with namedTemporaryDir(): metadata = {} manifest = self.make_manifest(metadata) metadata[sd.DMDK_SDUUID] = manifest.sdUUID self.assertEquals(manifest.sdUUID, manifest.getMetaParam(sd.DMDK_SDUUID))
def test_getallimages(self): with namedTemporaryDir() as tmpdir: manifest = make_filesd_manifest(tmpdir) self.assertEqual(set(), manifest.getAllImages()) img_uuid = str(uuid.uuid4()) make_file_volume(manifest.domaindir, VOLSIZE, img_uuid) self.assertIn(img_uuid, manifest.getAllImages())
def test_unsafe_create_volume(self): with namedTemporaryDir() as tmpdir: path = os.path.join(tmpdir, 'test.qcow2') # Using unsafe=True to verify that it is possible to create an # image based on a non-existing backing file, like an inactive LV. qemuimg.create(path, size=1048576, format=qemuimg.FORMAT.QCOW2, backing='no-such-file', unsafe=True)
def test_teardown_failure(self): job_id = make_uuid() sp_id = make_uuid() sd_id = make_uuid() img0_id = make_uuid() img1_id = TEARDOWN_ERROR_IMAGE_ID vol0_id = make_uuid() vol1_id = make_uuid() images = [ {'sd_id': sd_id, 'img_id': img0_id, 'vol_id': vol0_id}, {'sd_id': sd_id, 'img_id': img1_id, 'vol_id': vol1_id}, ] expected = [ ('prepareImage', (sd_id, sp_id, img0_id, vol0_id), {'allowIllegal': True}), ('prepareImage', (sd_id, sp_id, img1_id, vol1_id), {'allowIllegal': True}), ('teardownImage', (sd_id, sp_id, img1_id), {}), ('teardownImage', (sd_id, sp_id, img0_id), {}), ] with namedTemporaryDir() as base: irs = FakeIRS(base) job = seal.Job(job_id, sp_id, images, irs) job.autodelete = False job.run() wait_for_job(job) self.assertEqual(jobs.STATUS.FAILED, job.status) self.assertEqual(expected, irs.__calls__)
def test_create_new(self): with namedTemporaryDir() as tmpdir: target = os.path.join(tmpdir, "target") link = os.path.join(tmpdir, "link") fileUtils.atomic_symlink(target, link) self.assertEqual(os.readlink(link), target) self.assertFalse(os.path.exists(link + ".tmp"))
def test_error_isfile(self): with namedTemporaryDir() as tmpdir: target = os.path.join(tmpdir, "target") link = os.path.join(tmpdir, "link") with open(link, 'w') as f: f.write('data') self.assertRaises(OSError, fileUtils.atomic_symlink, target, link)
def test_no_match(self, img_format): with namedTemporaryDir() as tmpdir: path = os.path.join(tmpdir, 'test') qemuimg.create(path, '1m', img_format) qemu_pattern_write(path, img_format, pattern=2) self.assertRaises(ChainVerificationError, qemu_pattern_verify, path, img_format, pattern=4)
def test_getreaddelay(self): with namedTemporaryDir() as tmpdir: lvm = FakeLVM(tmpdir) with MonkeyPatchScope([(blockSD, 'lvm', lvm)]): manifest = make_blocksd(tmpdir, lvm) vg_name = manifest.sdUUID make_file(lvm.lvPath(vg_name, 'metadata')) self.assertIsInstance(manifest.getReadDelay(), float)
def test_metaslot_lock(self): with namedTemporaryDir() as tmpdir: lvm = FakeLVM(tmpdir) with MonkeyPatchScope([(blockSD, 'lvm', lvm)]): manifest = make_blocksd(tmpdir, lvm) with manifest.acquireVolumeMetadataSlot(None, 1): acquired = manifest._lvTagMetaSlotLock.acquire(False) self.assertFalse(acquired)
def test_getHookInfo(self): with namedTemporaryDir() as dir: sName, md5 = self.createScript(dir) with tempfile.NamedTemporaryFile(dir=dir) as NEscript: os.chmod(NEscript.name, 0o000) info = hooks._getHookInfo(dir) expectedRes = dict([(os.path.basename(sName), {"md5": md5})]) self.assertEqual(expectedRes, info)
def testSuccessfulImportOVA(self): with temporary_ovf_dir() as ovapath, \ namedTemporaryDir() as v2v._LOG_DIR: v2v.convert_ova(ovapath, self.vminfo, self.job_id, FakeIRS()) job = v2v._jobs[self.job_id] job.wait() self.assertEqual(job.status, v2v.STATUS.DONE)
def test_unsafe_info(self, unsafe): with namedTemporaryDir() as tmpdir: img = os.path.join(tmpdir, 'img.img') size = 1048576 op = qemuimg.create(img, size=size, format=qemuimg.FORMAT.QCOW2) op.run() info = qemuimg.info(img, unsafe=unsafe) assert size == info['virtualsize']
def test_untrusted_image(self): with namedTemporaryDir() as tmpdir: img = os.path.join(tmpdir, 'untrusted.img') size = 500 * 1024**3 op = qemuimg.create(img, size=size, format=qemuimg.FORMAT.QCOW2) op.run() info = qemuimg.info(img, trusted_image=False) assert size == info['virtualsize']
def test_ppc_device_tree_parsing(self, test_input, expected_result): with namedTemporaryDir() as tmpdir: with tempfile.NamedTemporaryFile(dir=tmpdir) as f: f.write(test_input) f.flush() result = ppc64HardwareInfo._from_device_tree( os.path.basename(f.name), tree_path=tmpdir) self.assertEqual(expected_result, result)
def test_createdir_no_mode(): with namedTemporaryDir() as base: path = os.path.join(base, "a", "b") assert not os.path.isdir(path) fileUtils.createdir(path) assert os.path.isdir(path)
def testGetBootProtocolUnified(self): with namedTemporaryDir() as tempDir: netsDir = os.path.join(tempDir, 'nets') os.mkdir(netsDir) networks = { 'nonVMOverNic': { "nic": "eth0", "bridged": False, "bootproto": "dhcp" }, 'bridgeOverNic': { "nic": "eth1", "bridged": True }, 'nonVMOverBond': { "bonding": "bond0", "bridged": False, "bootproto": "dhcp" }, 'bridgeOverBond': { "bonding": "bond1", "bridged": True }, 'vlanOverNic': { "nic": "eth2", "bridged": False, "vlan": 1, "bootproto": "dhcp" }, 'bridgeOverVlan': { "nic": "eth3", "bridged": True, "vlan": 1 }, 'vlanOverBond': { "bonding": "bond2", "bridged": False, "bootproto": "dhcp", "vlan": 1 }, 'bridgeOverVlanOverBond': { "bonding": "bond3", "bridged": True, "vlan": 1 } } with MonkeyPatchScope([(netconfpersistence, 'CONF_RUN_DIR', tempDir)]): runningConfig = netconfpersistence.RunningConfig() for network, attributes in networks.iteritems(): runningConfig.setNetwork(network, attributes) runningConfig.save() for network, attributes in networks.iteritems(): if attributes.get('bridged') == 'true': topLevelDevice = network else: topLevelDevice = attributes.get('nic') or \ attributes.get('bonding') if attributes.get('vlan'): topLevelDevice += '.%s' % attributes.get('vlan') self.assertEqual( getBootProtocol(topLevelDevice, 'unified'), attributes.get('bootproto'))
def _fake_ifcfgs(): with namedTemporaryDir() as temp_dir: for iface, conf in FAKE_IFCFGS.iteritems(): with open(os.path.join(temp_dir, 'ifcfg-' + iface), 'w') as f: f.write(conf) yield temp_dir
def test_bad_args(self, exception, fn, args): with namedTemporaryDir() as tmpdir: lvm = FakeLVM(tmpdir) lvm_fn = getattr(lvm, fn) self.assertRaises(exception, lvm_fn, *args)
def setup_env(self): with fake.VM() as testvm, namedTemporaryDir() as tmpdir: with MonkeyPatchScope([(constants, 'P_VDSM_RUN', tmpdir)]): yield testvm, tmpdir
def test_emptyDir(self): with namedTemporaryDir() as dirName: DOMXML = "algo" self.assertEqual(DOMXML, hooks._runHooksDir(DOMXML, dirName))
def test_getreaddelay(self): with namedTemporaryDir() as tmpdir: manifest = make_filesd_manifest(tmpdir) self.assertIsInstance(manifest.getReadDelay(), float)
def test_getvallocsize(self): with namedTemporaryDir() as tmpdir: manifest = make_filesd_manifest(tmpdir) imguuid, voluuid = make_file_volume(manifest.domaindir, VOLSIZE) self.assertEqual(0, manifest.getVAllocSize(imguuid, voluuid))
def test_getisodomainimagesdir(self): with namedTemporaryDir() as tmpdir: manifest = make_filesd_manifest(tmpdir) isopath = os.path.join(manifest.domaindir, sd.DOMAIN_IMAGES, sd.ISO_IMAGE_UUID) self.assertEquals(isopath, manifest.getIsoDomainImagesDir())
def test_createdir_directory_exists_other_mode(): with namedTemporaryDir() as base: with pytest.raises(OSError) as e: fileUtils.createdir(base, mode=0o755) assert e.value.errno == errno.EPERM
def testGetDhclientIfaces(self): LEASES = ( 'lease {{\n' ' interface "valid";\n' ' expire {active_datetime:%w %Y/%m/%d %H:%M:%S};\n' '}}\n' 'lease {{\n' ' interface "valid2";\n' ' expire epoch {active:.0f}; # Sat Jan 31 20:04:20 2037\n' '}}\n' # human-readable date is just a comment 'lease {{\n' ' interface "valid3";\n' ' expire never;\n' '}}\n' 'lease {{\n' ' interface "expired";\n' ' expire {expired_datetime:%w %Y/%m/%d %H:%M:%S};\n' '}}\n' 'lease {{\n' ' interface "expired2";\n' ' expire epoch {expired:.0f}; # Fri Jan 31 20:04:20 2014\n' '}}\n' 'lease6 {{\n' ' interface "valid4";\n' ' ia-na [some MAC address] {{\n' ' iaaddr [some IPv6 address] {{\n' ' starts {now:.0f};\n' ' max-life 60;\n' # the lease has a minute left ' }}\n' ' }}\n' '}}\n' 'lease6 {{\n' ' interface "expired3";\n' ' ia-na [some MAC address] {{\n' ' iaaddr [some IPv6 address] {{\n' ' starts {expired:.0f};\n' ' max-life 30;\n' # the lease expired half a minute ago ' }}\n' ' }}\n' '}}\n') with namedTemporaryDir() as tmp_dir: lease_file = os.path.join(tmp_dir, 'test.lease') with open(lease_file, 'w') as f: now = time.time() last_minute = now - 60 next_minute = now + 60 f.write( LEASES.format( active_datetime=datetime.utcfromtimestamp(next_minute), active=next_minute, expired_datetime=datetime.utcfromtimestamp( last_minute), expired=last_minute, now=now)) dhcpv4_ifaces, dhcpv6_ifaces = \ netinfo._get_dhclient_ifaces([lease_file]) self.assertIn('valid', dhcpv4_ifaces) self.assertIn('valid2', dhcpv4_ifaces) self.assertIn('valid3', dhcpv4_ifaces) self.assertNotIn('expired', dhcpv4_ifaces) self.assertNotIn('expired2', dhcpv4_ifaces) self.assertIn('valid4', dhcpv6_ifaces) self.assertNotIn('expired3', dhcpv6_ifaces)
def test_getblocksize_defaults(self): with namedTemporaryDir() as tmpdir: manifest = make_blocksd_manifest(tmpdir) self.assertEquals(512, manifest.logBlkSize) self.assertEquals(512, manifest.phyBlkSize)
def test_createdir_directory_exists_other_mode(): with namedTemporaryDir() as base: with pytest.raises(OSError): fileUtils.createdir(base, mode=0o755)
def test_error_isdir(self): with namedTemporaryDir() as tmpdir: target = os.path.join(tmpdir, "target") link = os.path.join(tmpdir, "link") os.mkdir(link) self.assertRaises(OSError, fileUtils.atomic_symlink, target, link)
def test_zero_size(self): # Test that fallocate call throws exception on error with namedTemporaryDir() as tmpdir: image = os.path.join(tmpdir, "image") with self.assertRaises(cmdutils.Error): fallocate.allocate(image, 0).run()
def test_create_dirs_no_mode(self): with namedTemporaryDir() as base: path = os.path.join(base, "a", "b") self.assertFalse(os.path.isdir(path)) fileUtils.createdir(path) self.assertTrue(os.path.isdir(path))
def test_create_raise_errors(self): with namedTemporaryDir() as base: path = os.path.join(base, "a", "b") self.assertRaises(OSError, fileUtils.createdir, path, 0o400)
def test_getmdpath(self): with namedTemporaryDir() as tmpdir: manifest = make_filesd_manifest(tmpdir) mdpath = os.path.join(manifest.domaindir, sd.DOMAIN_META_DATA) self.assertEquals(mdpath, manifest.getMDPath())
def make_leases(): with namedTemporaryDir() as tmpdir: path = os.path.join(tmpdir, "xleases") with io.open(path, "wb") as f: f.truncate(xlease.INDEX_SIZE) yield path
def make_leases(): with namedTemporaryDir() as tmpdir: path = os.path.join(tmpdir, "xleases") with io.open(path, "wb") as f: f.truncate(constants.GIB) yield path
def test_createdir_file_exists_no_mode(): with namedTemporaryDir() as base: path = os.path.join(base, "file") with open(path, "w"): with pytest.raises(OSError): fileUtils.createdir(path)