コード例 #1
0
ファイル: miscTests.py プロジェクト: mpolednik/vdsm
    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)
コード例 #2
0
 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)
コード例 #3
0
    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)
コード例 #4
0
ファイル: miscTests.py プロジェクト: mpolednik/vdsm
 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)
コード例 #5
0
ファイル: hooksTests.py プロジェクト: futurice/vdsm
 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)
コード例 #6
0
ファイル: vmTests.py プロジェクト: int64ago-public/vdsm
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)
コード例 #7
0
ファイル: vmTests.py プロジェクト: humblec/vdsm
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)
コード例 #8
0
ファイル: hooksTests.py プロジェクト: vinzenz/vdsm
 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)
コード例 #9
0
ファイル: miscTests.py プロジェクト: mpolednik/vdsm
 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))
コード例 #10
0
 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))
コード例 #11
0
ファイル: vmTests.py プロジェクト: fzkbass/vdsm
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
コード例 #12
0
ファイル: vmTests.py プロジェクト: mpolednik/vdsm
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
コード例 #13
0
 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()
コード例 #14
0
ファイル: hooksTests.py プロジェクト: futurice/vdsm
    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
コード例 #15
0
ファイル: sosPluginTests.py プロジェクト: vinzenz/vdsm
    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")
コード例 #16
0
ファイル: netinfoTests.py プロジェクト: fzkbass/vdsm
    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')
コード例 #17
0
ファイル: netinfoTests.py プロジェクト: zhangguoqing/vdsm
    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')
コード例 #18
0
ファイル: hooksTests.py プロジェクト: vinzenz/vdsm
    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
コード例 #19
0
ファイル: hooksTests.py プロジェクト: vinzenz/vdsm
    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
コード例 #20
0
ファイル: hooksTests.py プロジェクト: futurice/vdsm
    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
コード例 #21
0
    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))
コード例 #22
0
ファイル: miscTests.py プロジェクト: mpolednik/vdsm
    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))
コード例 #23
0
ファイル: sosPluginTests.py プロジェクト: vinzenz/vdsm
    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")
コード例 #24
0
ファイル: netinfoTests.py プロジェクト: zhangguoqing/vdsm
    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'))
コード例 #25
0
ファイル: netinfoTests.py プロジェクト: zhangguoqing/vdsm
    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)
コード例 #26
0
ファイル: netinfoTests.py プロジェクト: fzkbass/vdsm
    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)
コード例 #27
0
ファイル: netinfoTests.py プロジェクト: humblec/vdsm
    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)
コード例 #28
0
ファイル: netinfoTests.py プロジェクト: fzkbass/vdsm
    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)
コード例 #29
0
ファイル: netinfoTests.py プロジェクト: fzkbass/vdsm
    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'))
コード例 #30
0
ファイル: hooksTests.py プロジェクト: futurice/vdsm
 def test_emptyDir(self):
     with namedTemporaryDir() as dirName:
         DOMXML = "algo"
         self.assertEqual(DOMXML, hooks._runHooksDir(DOMXML, dirName))
コード例 #31
0
ファイル: hooksTests.py プロジェクト: vinzenz/vdsm
 def test_emptyDir(self):
     with namedTemporaryDir() as dirName:
         DOMXML = "algo"
         self.assertEqual(DOMXML, hooks._runHooksDir(DOMXML, dirName))