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 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_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 FakeVM(params=None): with namedTemporaryDir() as tmpDir: with MonkeyPatchScope([(constants, 'P_VDSM_RUN', tmpDir), (libvirtconnection, 'get', lambda x: ConnectionMock())]): vmParams = {'vmId': 'TESTING'} vmParams.update({} if params is None else params) yield vm.Vm(None, vmParams)
def FakeVM(params=None): with namedTemporaryDir() as tmpDir: with MonkeyPatchScope( [(constants, "P_VDSM_RUN", tmpDir + "/"), (libvirtconnection, "get", lambda x: ConnectionMock())] ): vmParams = {"vmId": "TESTING"} vmParams.update({} if params is None else params) yield vm.Vm(None, vmParams)
def testEmptyDir(self): """ Test if method can delete an empty dir. """ with namedTemporaryDir() as baseDir: dirty = os.path.join(baseDir, 'dirty') os.mkdir(dirty) fileUtils.cleanupdir(dirty) self.assertFalse(os.path.lexists(dirty))
def FakeVM(params=None, devices=None, runCpu=False): with namedTemporaryDir() as tmpDir: with MonkeyPatchScope([(constants, 'P_VDSM_RUN', tmpDir + '/'), (libvirtconnection, 'get', ConnectionMock)]): vmParams = {'vmId': 'TESTING'} vmParams.update({} if params is None else params) fake = vm.Vm(None, vmParams) fake.guestAgent = FakeGuestAgent() fake.conf['devices'] = [] if devices is None else devices fake._guestCpuRunning = runCpu yield fake
def testLoopMount(self): checkSudo(["mount", "-o", "loop", "somefile", "target"]) checkSudo(["umount", "target"]) 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) m.mount(mntOpts="loop") try: self.assertTrue(m.isMounted()) finally: m.umount()
def tempScripts(self): with namedTemporaryDir() as dirName: Q = 3 code = """#! /bin/bash echo -n %s >> "$_hook_domxml" """ scripts = [tempfile.NamedTemporaryFile(dir=dirName, delete=False) for n in xrange(Q)] scripts.sort(key=lambda f: f.name) for n, script in enumerate(scripts): script.write(code % n) os.chmod(os.path.join(dirName, script.name), 0o775) script.close() yield dirName, scripts
def testSosPlugin(self): with namedTemporaryDir() as tmpDir: cmd = ["sosreport", "-o", "vdsm", "--batch", "--name", ARCHIVE_NAME, "--tmp-dir", tmpDir] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) (stdout, stderr) = p.communicate() if p.returncode: self.fail("Failed with executed sosreport, return code: %d" % p.returncode) # When sos plugin raise exception, sosreport still exit with # successful and print exception to stdout. So check the keyword of # exception in output. index = stdout.find("Traceback (most recent call last):") self.assertEquals(index, -1, "sosreport raised an exception")
def testGetIfaceCfg(self): deviceName = "___This_could_never_be_a_device_name___" ifcfg = ('GATEWAY0=1.1.1.1\n' 'NETMASK=255.255.0.0\n') with namedTemporaryDir() as tempDir: ifcfgPrefix = os.path.join(tempDir, 'ifcfg-') filePath = ifcfgPrefix + deviceName with MonkeyPatchScope([(netinfo, 'NET_CONF_PREF', ifcfgPrefix)]): with open(filePath, 'w') as ifcfgFile: ifcfgFile.write(ifcfg) self.assertEqual( netinfo.getIfaceCfg(deviceName)['GATEWAY'], '1.1.1.1') self.assertEqual( netinfo.getIfaceCfg(deviceName)['NETMASK'], '255.255.0.0')
def _deviceCustomPropertiesTestFile(self): with namedTemporaryDir() as dirName: # two nested with blocks to be python 2.6 friendly with tempfile.NamedTemporaryFile(dir=dirName, delete=False) as f: code = """#!/usr/bin/python import os import hooking domXMLFile = file(os.environ['_hook_domxml'], 'a') customProperty = os.environ['customProperty'] domXMLFile.write(customProperty) """ f.write(code) os.chmod(f.name, 0o775) yield dirName
def tempScripts(self): with namedTemporaryDir() as dirName: Q = 3 code = """#! /bin/bash echo -n %s >> "$_hook_domxml" """ scripts = [ tempfile.NamedTemporaryFile(dir=dirName, delete=False) for n in xrange(Q) ] scripts.sort(key=lambda f: f.name) for n, script in enumerate(scripts): script.write(code % n) os.chmod(os.path.join(dirName, script.name), 0o775) script.close() yield dirName, scripts
def testFullDir(self): """ Test if method can clean a dir it should be able to. """ with namedTemporaryDir() as baseDir: # Populate dir dirty = os.path.join(baseDir, 'dirty') os.mkdir(dirty) numOfFilesToCreate = 50 for i in range(numOfFilesToCreate): tempfile.mkstemp(dir=dirty) # clean it fileUtils.cleanupdir(dirty) self.assertFalse(os.path.lexists(dirty))
def testSosPlugin(self): with namedTemporaryDir() as tmpDir: cmd = [ "sosreport", "-o", "vdsm", "--batch", "--name", ARCHIVE_NAME, "--tmp-dir", tmpDir ] p = subprocess.Popen(cmd, stdout=subprocess.PIPE) (stdout, stderr) = p.communicate() if p.returncode: self.fail("Failed with executed sosreport, return code: %d" % p.returncode) # When sos plugin raise exception, sosreport still exit with # successful and print exception to stdout. So check the keyword of # exception in output. index = stdout.find('Traceback (most recent call last):') self.assertEquals(index, -1, "sosreport raised an exception")
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 testGetBootProtocolIfcfg(self): deviceName = "___This_could_never_be_a_device_name___" ifcfg = ('DEVICE=%s' % deviceName + '\n' + 'ONBOOT=yes' + '\n' + 'MTU=1500' + '\n' + 'HWADDR=5e:64:6d:12:16:84' + '\n') with namedTemporaryDir() as tempDir: ifcfgPrefix = os.path.join(tempDir, 'ifcfg-') filePath = ifcfgPrefix + deviceName with MonkeyPatchScope([(netinfo, 'NET_CONF_PREF', ifcfgPrefix)]): with open(filePath, 'w') as ifcfgFile: ifcfgFile.write(ifcfg + 'BOOTPROTO=dhcp\n') self.assertEqual(getBootProtocol(deviceName, 'ifcfg'), 'dhcp') with open(filePath, 'w') as ifcfgFile: ifcfgFile.write(ifcfg + 'BOOTPROTO=none\n') self.assertEqual(getBootProtocol(deviceName, 'ifcfg'), 'none') with open(filePath, 'w') as ifcfgFile: ifcfgFile.write(ifcfg) self.assertEqual(getBootProtocol(deviceName, 'ifcfg'), None)
def testGetDhclientIfaces(self): LEASES = ( 'lease {{\n' ' interface "valid";\n' ' expire {0:%w %Y/%m/%d %H:%M:%S};\n' '}}\n' 'lease {{\n' ' interface "valid2";\n' ' expire epoch {1:.0f}; # Sat Jan 31 20:04:20 2037\n' '}}\n' # human-readable date is just a comment 'lease {{\n' ' interface "expired";\n' ' expire {2:%w %Y/%m/%d %H:%M:%S};\n' '}}\n' 'lease {{\n' ' interface "expired2";\n' ' expire epoch {3:.0f}; # Fri Jan 31 20:04:20 2014\n' '}}\n' ) with namedTemporaryDir() as tmpDir: leaseFile = os.path.join(tmpDir, 'test.lease') with open(leaseFile, 'w') as f: lastMinute = time.time() - 60 nextMinute = time.time() + 60 f.write(LEASES.format( datetime.utcfromtimestamp(nextMinute), nextMinute, datetime.utcfromtimestamp(lastMinute), lastMinute )) dhcp4 = getDhclientIfaces([leaseFile]) self.assertIn('valid', dhcp4) self.assertIn('valid2', dhcp4) self.assertNotIn('expired', dhcp4) self.assertNotIn('expired2', dhcp4)
def testGetDhclientIfaces(self): LEASES = ( 'lease {{\n' ' interface "valid";\n' ' expire {0:%w %Y/%m/%d %H:%M:%S};\n' '}}\n' 'lease {{\n' ' interface "valid2";\n' ' expire epoch {1:.0f}; # Sat Jan 31 20:04:20 2037\n' '}}\n' # human-readable date is just a comment 'lease {{\n' ' interface "expired";\n' ' expire {2:%w %Y/%m/%d %H:%M:%S};\n' '}}\n' 'lease {{\n' ' interface "expired2";\n' ' expire epoch {3:.0f}; # Fri Jan 31 20:04:20 2014\n' '}}\n') with namedTemporaryDir() as tmpDir: leaseFile = os.path.join(tmpDir, 'test.lease') with open(leaseFile, 'w') as f: lastMinute = time.time() - 60 nextMinute = time.time() + 60 f.write( LEASES.format(datetime.utcfromtimestamp(nextMinute), nextMinute, datetime.utcfromtimestamp(lastMinute), lastMinute)) dhcp4 = getDhclientIfaces([leaseFile]) self.assertIn('valid', dhcp4) self.assertIn('valid2', dhcp4) self.assertNotIn('expired', dhcp4) self.assertNotIn('expired2', dhcp4)
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 test_emptyDir(self): with namedTemporaryDir() as dirName: DOMXML = "algo" self.assertEqual(DOMXML, hooks._runHooksDir(DOMXML, dirName))