Esempio n. 1
0
    def testCopy(self):
        """
        Test that regular copying works.
        """
        # Prepare source
        data = "Everything starts somewhere, " + \
               "though many physicists disagree." + \
               "But people have always been dimly aware of the " + \
               "problem with the start of things." + \
               "They wonder how the snowplough driver gets to work, or " + \
               "how the makers of dictionaries look up the spelling of words."
        # (C) Terry Pratchet - Small Gods

        # Makes sure we round up to a complete block size
        data *= 512

        with temporaryPath(perms=0o666, data=data) as srcPath:
            with temporaryPath(perms=0o666) as dstPath:
                # Copy
                rc, out, err = misc.ddWatchCopy(srcPath, dstPath,
                                                None, len(data))

                # Get copied data
                with open(dstPath) as f:
                    readData = f.read()

        # Comapre
        self.assertEqual(readData, data)
Esempio n. 2
0
    def testNonAlignedCopy(self):
        """
        Test that copying a file with odd length works.
        """

        data = '- "What\'re quantum mechanics?"' + \
               '- "I don\'t know. People who repair quantums, I suppose."'
        # (C) Terry Pratchet - Small Gods

        # Make sure the length is appropriate
        if (len(data) % 512) == 0:
            data += "!"

        with temporaryPath(perms=0o666, data=data) as srcPath:
            with temporaryPath(perms=0o666) as dstPath:
                # Copy
                rc, out, err = misc.ddWatchCopy(srcPath, dstPath,
                                                None, len(data))

                # Get copied data
                with open(dstPath) as dp:
                    readData = dp.read()

        # Compare
        self.assertEqual(readData, data)
Esempio n. 3
0
    def testSmallWrites(self):
        data = """
        Aliquet habitasse tellus. Fringilla faucibus tortor parturient
        consectetuer sodales, venenatis platea habitant. Hendrerit nostra nunc
        odio. Primis porttitor consequat enim ridiculus. Taciti nascetur,
        nibh, convallis sit, cum dis mi. Nonummy justo odio cursus, ac hac
        curabitur nibh. Tellus. Montes, ut taciti orci ridiculus facilisis
        nunc. Donec. Risus adipiscing habitant donec vehicula non vitae class,
        porta vitae senectus. Nascetur felis laoreet integer, tortor ligula.
        Pellentesque vestibulum cras nostra. Ut sollicitudin posuere, per
        accumsan curabitur id, nisi fermentum vel, eget netus tristique per,
        donec, curabitur senectus ut fusce. A. Mauris fringilla senectus et
        eni facilisis magna inceptos eu, cursus habitant fringilla neque.
        Nibh. Elit facilisis sed, elit, nostra ve torquent dictumst, aenean
        sapien quam, habitasse in. Eu tempus aptent, diam, nisi risus
        pharetra, ac, condimentum orci, consequat mollis. Cras lacus augue
        ultrices proin fermentum nibh sed urna. Ve ipsum ultrices curae,
        feugiat faucibus proin et elementum vivamus, lectus. Torquent. Tempus
        facilisi. Cras suspendisse euismod consectetuer ornare nostra. Fusce
        amet cum amet diam.
        """
        self.assertTrue(len(data) > 512)

        with temporaryPath() as srcPath:
            with fileUtils.open_ex(srcPath, "dw") as f:
                f.write(data[:512])
                f.write(data[512:])

            with fileUtils.open_ex(srcPath, "r") as f:
                self.assertEquals(f.read(len(data)), data)
Esempio n. 4
0
 def testCopyUserModeToGroup(self):
     with temporaryPath() as path:
         for initialMode, expectedMode in self.modesList:
             os.chmod(path, initialMode)
             fileUtils.copyUserModeToGroup(path)
             self.assertEquals(os.stat(path).st_mode & self.MODE_MASK,
                               expectedMode)
Esempio n. 5
0
    def testUpdateRead(self):
        data = """
        Aliquet. Aliquam eni ac nullam iaculis cras ante, adipiscing. Enim
        eget egestas pretium. Ultricies. Urna cubilia in, hac. Curabitur.
        Nibh. Purus ridiculus natoque sed id. Feugiat lacus quam, arcu
        maecenas nec egestas. Hendrerit duis nunc eget dis lacus porttitor per
        sodales class diam condimentum quisque condimentum nisi ligula.
        Dapibus blandit arcu nam non ac feugiat diam, dictumst. Ante eget
        fames eu penatibus in, porta semper accumsan adipiscing tellus in
        sagittis. Est parturient parturient mi fermentum commodo, per
        fermentum. Quis duis velit at quam risus mi. Facilisi id fames.
        Turpis, conubia rhoncus. Id. Elit eni tellus gravida, ut, erat morbi.
        Euismod, enim a ante vestibulum nibh. Curae curae primis vulputate
        adipiscing arcu ipsum suspendisse quam hymenaeos primis accumsan
        vestibulum.
        """
        self.assertTrue(len(data) > 512)

        with temporaryPath() as srcPath:
            with fileUtils.open_ex(srcPath, "wd") as f:
                f.write(data[:512])

            with fileUtils.open_ex(srcPath, "r+d") as f:
                f.seek(512)
                f.write(data[512:])

            with fileUtils.open_ex(srcPath, "r") as f:
                self.assertEquals(f.read(len(data)), data)
Esempio n. 6
0
    def test_small_writes(self):
        with temporaryPath() as srcPath, directio.DirectFile(srcPath, "w") as f:
            f.write(self.DATA[:BLOCK_SIZE])
            f.write(self.DATA[BLOCK_SIZE:])

            with io.open(srcPath, "rb") as f:
                self.assertEquals(f.read(), self.DATA)
Esempio n. 7
0
def fake_dd(delay):
    script = "#!/bin/sh\nsleep %.1f\n" % delay
    script = script.encode('ascii')
    with temporaryPath(data=script) as fake_dd:
        os.chmod(fake_dd, 0o700)
        with MonkeyPatchScope([(constants, "EXT_DD", fake_dd)]):
            yield
Esempio n. 8
0
 def testRead(self):
     data = """Vestibulum. Libero leo nostra, pede nunc eu. Pellentesque
     platea lacus morbi nisl montes ve. Ac. A, consectetuer erat, justo eu.
     Elementum et, phasellus fames et rutrum donec magnis eu bibendum. Arcu,
     ante aliquam ipsum ut facilisis ad."""
     with temporaryPath(data=data) as srcPath, \
             fileUtils.open_ex(srcPath, "dr") as f:
         self.assertEquals(f.read(), data)
Esempio n. 9
0
    def test_write_domxml(self, monkeypatch):
        with temporaryPath() as path:
            monkeypatch.setenv('_hook_domxml', path)
            hooking.write_domxml(minidom.parseString(self._EXPECTED_XML))

            with io.open(path, 'r') as src:
                found_xml = src.read()
        assert xml_equal(found_xml, self._EXPECTED_XML)
Esempio n. 10
0
 def test_taskset_missing(self):
     self.checks = 1
     with temporaryPath(data=b"blah") as path:
         checker = check.DirectioChecker(self.loop, path, self.complete)
         checker.start()
         self.loop.run_forever()
         pprint.pprint(self.results)
         result = self.results[0]
         self.assertRaises(exception.MiscFileReadException, result.delay)
Esempio n. 11
0
    def test_roundtrip_domxml(self, monkeypatch):
        with temporaryPath() as path:
            os.environ['_hook_domxml'] = path
            monkeypatch.setenv('_hook_domxml', path)

            hooking.write_domxml(minidom.parseString(self._EXPECTED_XML))
            domxml = hooking.read_domxml()

        assert xml_equal(domxml.toprettyxml(), self._EXPECTED_XML)
Esempio n. 12
0
 def testWrite(self):
     data = """In ut non platea egestas, quisque magnis nunc nostra ac etiam
     suscipit nec integer sociosqu. Fermentum. Ante orci luctus, ipsum
     ullamcorper enim arcu class neque inceptos class. Ut, sagittis
     torquent, commodo facilisi."""
     with temporaryPath() as srcPath, fileUtils.open_ex(srcPath, "dw") as f:
         f.write(data)
         with fileUtils.open_ex(srcPath, "r") as f:
             self.assertEquals(f.read(len(data)), data)
Esempio n. 13
0
 def test_allocate(self, image_format, allocation_mode, allocated_bytes):
     size = 16 * 1024 * 1024
     with temporaryPath() as image:
         op = qemuimg.create(image,
                             size=size,
                             format=image_format,
                             preallocation=allocation_mode)
         op.run()
         allocated = os.stat(image).st_blocks * 512
         assert allocated == allocated_bytes
Esempio n. 14
0
    def test_update_and_read(self):
        with temporaryPath() as srcPath, directio.DirectFile(srcPath, "w") as f:
            f.write(self.DATA[:BLOCK_SIZE])

            with directio.DirectFile(srcPath, "r+") as f:
                f.seek(BLOCK_SIZE)
                f.write(self.DATA[BLOCK_SIZE:])

            with io.open(srcPath, "rb") as f:
                self.assertEquals(f.read(), self.DATA)
Esempio n. 15
0
def env(enable='true', format='pstat', clock='cpu', builtins='false'):
    with temporaryPath() as filename:
        config = make_config([
            ('devel', 'cpu_profile_enable', enable),
            ('devel', 'cpu_profile_filename', filename),
            ('devel', 'cpu_profile_format', format),
            ('devel', 'cpu_profile_clock', clock),
            ('devel', 'cpu_profile_builtins', builtins),
        ])
        with MonkeyPatchScope([(cpu, 'config', config)]):
            yield filename
Esempio n. 16
0
 def test_path_ok(self):
     self.checks = 1
     with temporaryPath(data=b"blah") as path:
         checker = check.DirectioChecker(self.loop, path, self.complete)
         checker.start()
         self.loop.run_forever()
         pprint.pprint(self.results)
         result = self.results[0]
         delay = result.delay()
         print("delay:", delay)
         self.assertEqual(type(delay), float)
Esempio n. 17
0
    def testNames(self):
        # I convert to some id because I have no
        # idea what users are defined and what
        # there IDs are apart from root
        tmpId = 666
        with temporaryPath() as srcPath:
            fileUtils.chown(srcPath, tmpId, tmpId)
            stat = os.stat(srcPath)
            self.assertTrue(stat.st_uid == stat.st_gid == tmpId)

            fileUtils.chown(srcPath, "root", "root")
            stat = os.stat(srcPath)
            self.assertTrue(stat.st_uid == stat.st_gid == 0)
Esempio n. 18
0
    def test_hibernation_params(self):
        vmParams = {}
        vmParams.update(self.vmParams)
        extraParams = {
            'a': 42,
            'foo': ['bar'],
        }
        with temporaryPath(data=pickle.dumps(extraParams)) as path:
            vmParams['hiberVolHandle'] = path
            res = self.vm.create(vmParams)

        self.assertFalse(response.is_error(res))
        for param in extraParams:
            self.assertEqual(extraParams[param], vmParams[param])
Esempio n. 19
0
 def test_path_ok(self, checkers):
     self.checkers = checkers
     with temporaryPath(data=b"blah") as path:
         start = time.time()
         for i in range(checkers):
             checker = check.DirectioChecker(self.loop, path, self.complete)
             checker.start()
         self.loop.run_forever()
         elapsed = time.time() - start
         self.assertEqual(len(self.results), self.checkers)
         print("%d checkers: %f seconds" % (checkers, elapsed))
         # Make sure all succeeded
         for res in self.results:
             res.delay()
Esempio n. 20
0
    def test_hibernation_params_wrong_format(self):
        vmParams = {}
        vmParams.update(self.vmParams)

        refParams = copy.deepcopy(vmParams)
        refParams['restoreState'] = True  # to be added BY TESTS

        extraParams = ['a', 42]
        with temporaryPath(data=pickle.dumps(extraParams)) as path:
            vmParams['hiberVolHandle'] = path
            res = self.vm.create(vmParams)

        res = self.vm.create(vmParams)
        self.assertFalse(response.is_error(res))
        self.assertEqual(refParams, vmParams)
Esempio n. 21
0
    def test_resize(self):
        # Test that resize call actually works
        size = 4096
        with temporaryPath(data=b'x' * size) as image:
            fallocate.allocate(image, size, offset=size).run()

            with io.open(image, 'rb') as f:
                actual = f.read()

            expected = b'x' * size + b'\0' * size

            self.assertEqual(expected, actual)

            allocated = os.stat(image).st_blocks * 512
            self.assertEqual(allocated, size * 2)
Esempio n. 22
0
def fake_dd(delay):
    """
    Simulate slow dd read
    """
    rate = int(100 / delay) if delay else "Infinity"
    script = """#!/bin/sh
sleep {delay}
echo 0+1 records in >&2
echo 0+1 records out >&2
echo 100 bytes copied, {delay} s, {rate} B/s >&2
""".format(delay=delay, rate=rate)
    script = script.encode('ascii')
    with temporaryPath(data=script) as fake_dd:
        os.chmod(fake_dd, 0o700)
        with MonkeyPatchScope([(constants, "EXT_DD", fake_dd)]):
            yield
Esempio n. 23
0
    def testVmWithCdrom(self, pathLocation):
        customization = {
            "vmId": "77777777-ffff-3333-bbbb-222222222222",
            "devices": [],
            "vmName": "testVmWithCdrom_%s" % pathLocation,
            "display": _GRAPHICS_FOR_ARCH[platform.machine()],
        }

        # echo -n testPayload | md5sum
        # d37e46c24c78b1aed33496107afdb44b
        vmPayloadName = "/var/run/vdsm/payload/%s." "d37e46c24c78b1aed33496107afdb44b" ".img" % customization["vmId"]

        cdrom = {
            "index": "2",
            "iface": "ide",
            "specParams": {},
            "readonly": "true",
            "path": "",
            "device": "cdrom",
            "shared": "false",
            "type": "disk",
        }

        with temporaryPath(0o666) as path:
            cdromPaths = {
                "self": {"path": path, "specParams": {"path": "/dev/null"}},
                "specParams": {"path": "", "specParams": {"path": path}},
                "vmPayload": {
                    "path": "",
                    "specParams": {"path": "", "vmPayload": {"volId": "testConfig", "file": {"testPayload": ""}}},
                },
            }
            cdrom.update(cdromPaths[pathLocation])
            customization["devices"].append(cdrom)

            with RunningVm(self.vdsm, customization) as vm:
                self._waitForStartup(vm, 10)
                self._verifyDevices(vm)

                status, msg, stats = self.vdsm.getVmList(vm)
                self.assertEqual(status, SUCCESS, msg)
                for device in stats["devices"]:
                    if device["device"] == "cdrom":
                        if "vmPayload" in cdrom["specParams"]:
                            cdrom["path"] = vmPayloadName
                        self.assertEqual(device["path"], cdrom["path"])
                        self.assertEqual(device["specParams"]["path"], cdrom["specParams"]["path"])
Esempio n. 24
0
def fake_mounts(mount_lines):
    """
    This method gets a list of mount lines,
    fakes the /proc/mounts and /etc/mtab files
    using monkey patch with a temporary file,
    and cleans everything on the end of use.

    Usage example:
    with fake_mounts([mount_line_1, mount_line_2]):
        <do something with /proc/mounts or /etc/mtab>
    """
    data = b"".join(line + b"\n" for line in mount_lines)
    with temporaryPath(data=data) as fake_mounts:
        with monkeypatch.MonkeyPatchScope([
            (mount, '_PROC_MOUNTS_PATH', fake_mounts),
        ]):
            yield
Esempio n. 25
0
    def testVmWithCdrom(self, pathLocation):
        customization = {'vmId': '77777777-ffff-3333-bbbb-222222222222',
                         'devices': [],
                         'vmName':
                         'testVmWithCdrom_%s' % pathLocation,
                         'display': _GRAPHICS_FOR_ARCH[platform.machine()]}

        # echo -n testPayload | md5sum
        # d37e46c24c78b1aed33496107afdb44b
        vmPayloadName = ('/var/run/vdsm/payload/%s.'
                         'd37e46c24c78b1aed33496107afdb44b'
                         '.img' % customization['vmId'])

        cdrom = {'index': '2', 'iface': 'ide', 'specParams':
                 {}, 'readonly': 'true', 'path':
                 '', 'device': 'cdrom', 'shared':
                 'false', 'type': 'disk'}

        with temporaryPath(0o666) as path:
            cdromPaths = {'self': {'path': path, 'specParams':
                                   {'path': '/dev/null'}},
                          'specParams': {'path': '', 'specParams':
                                         {'path': path}},
                          'vmPayload': {'path': '', 'specParams':
                                        {'path': '',
                                         'vmPayload': {'volId': 'testConfig',
                                                       'file': {'testPayload':
                                                                ''}}}}}
            cdrom.update(cdromPaths[pathLocation])
            customization['devices'].append(cdrom)

            with RunningVm(self.vdsm, customization) as vm:
                self._waitForStartup(vm, 10)
                self._verifyDevices(vm)

                status, msg, stats = self.vdsm.getVmList(vm)
                self.assertEqual(status, SUCCESS, msg)
                for device in stats['devices']:
                    if device['device'] == 'cdrom':
                        if 'vmPayload' in cdrom['specParams']:
                            cdrom['path'] = vmPayloadName
                        self.assertEqual(device['path'], cdrom['path'])
                        self.assertEqual(device['specParams']['path'],
                                         cdrom['specParams']['path'])
Esempio n. 26
0
 def testSeekRead(self):
     data = """
     Habitasse ipsum at fusce litora metus, placerat dui purus aenean ante,
     ve. Pede hymenaeos ut primis cum, rhoncus, lectus, nunc. Vestibulum
     curabitur vitae etiam magna auctor velit, mi tempus vivamus orci eros.
     Pellentesque curabitur risus fermentum eget. Elementum curae, donec
     nisl egestas ve, ut odio eu nunc elit felis primis id. Ridiculus metus
     morbi nulla erat, amet nisi. Amet ligula nisi, id penatibus risus in.
     Purus velit duis. Aenean eget, pellentesque eu rhoncus arcu et
     consectetuer laoreet, augue nisi dictum lacinia urna. Fermentum
     torquent. Ut interdum vivamus duis. Felis consequat nec pede. Orci
     sollicitudin parturient orci felis. Enim, diam velit sapien
     condimentum fames semper nibh. Integer at, egestas pede consectetuer
     ac augue pharetra dolor non placerat quisque id cursus ultricies.
     Ligula mi senectus sit. Habitasse. Integer sollicitudin dapibus cum
     quam.
     """
     self.assertTrue(len(data) > 512)
     with temporaryPath(data=data) as srcPath, \
             fileUtils.open_ex(srcPath, "dr") as f:
         f.seek(512)
         self.assertEquals(f.read(), data[512:])
Esempio n. 27
0
 def testStringAsDrive(self):
     with temporaryPath() as f:
         volPath = self.cif.prepareVolumePath(f)
         self.assertEqual(volPath, f)
Esempio n. 28
0
 def test_write_unaligned(self):
     with temporaryPath(data=self.DATA) as srcPath, directio.DirectFile(srcPath, "r+") as f:
         self.assertRaises(ValueError, f.write, "x" * 511)
         with io.open(srcPath, "rb") as f:
             self.assertEqual(f.read(), self.DATA)
Esempio n. 29
0
 def test_read_all(self):
     with temporaryPath(data=self.DATA) as srcPath, directio.DirectFile(srcPath, "r") as direct_file, io.open(
         srcPath, "rb"
     ) as buffered_file:
         self.assertEquals(direct_file.read(), buffered_file.read())
Esempio n. 30
0
 def test(self):
     targetId = 666
     with temporaryPath() as srcPath:
         fileUtils.chown(srcPath, targetId, targetId)
         stat = os.stat(srcPath)
         self.assertTrue(stat.st_uid == stat.st_gid == targetId)