コード例 #1
0
    def testNonAlignedCopy(self, sudo=False):
        """
        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.assertEquals(readData, data)
コード例 #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)
コード例 #3
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)
コード例 #4
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.assertEquals(readData, data)
コード例 #5
0
 def testCopyUserModeToGroup(self):
     with temporaryPath() as path:
         for initialMode, expectedMode in self.modesList:
             os.chmod(path, initialMode)
             fileUtils.copyUserModeToGroup(path)
             self.assertEqual(
                 os.stat(path).st_mode & self.MODE_MASK, expectedMode)
コード例 #6
0
ファイル: check_test.py プロジェクト: gobindadas/vdsm
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
コード例 #7
0
ファイル: fileUtilTests.py プロジェクト: Caez83/vdsm
    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)
コード例 #8
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)
コード例 #9
0
ファイル: fileUtilTests.py プロジェクト: Caez83/vdsm
    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)
コード例 #10
0
ファイル: fileUtilTests.py プロジェクト: yingyun001/vdsm
 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)
コード例 #11
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)
コード例 #12
0
ファイル: storage_check_test.py プロジェクト: yingyun001/vdsm
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
コード例 #13
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)
コード例 #14
0
    def test_benchmark(self):
        setup = """
from vdsm.tool import confmeta
path = "%s"

def bench():
    confmeta.read_metadata(path)
"""
        data = b"""\
# This file is managed by vdsm
# Options:
#   ...
#   ...
#   ...
#REVISION: 1
#PRIVATE: NO

file body...
"""
        count = 100
        with temporaryPath(data=data) as path:
            elapsed = timeit.timeit("bench()",
                                    setup=setup % path,
                                    number=count)

        print("%.6f seconds (%.6f per op)" % (elapsed, elapsed / count))
コード例 #15
0
 def test_must_start_with_metadata(self):
     data = (b"There is no metadata here\n"
             b"#REVISION: 1\n"
             b"#PRIVATE: YES\n")
     with temporaryPath(data=data) as path:
         md = confmeta.read_metadata(path)
         self.assertEqual(md.revision, None)
         self.assertEqual(md.private, False)
コード例 #16
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)
コード例 #17
0
ファイル: fileUtilTests.py プロジェクト: kanalun/vdsm
 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)
コード例 #18
0
ファイル: hooking_test.py プロジェクト: wuyeliang/vdsm
    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)
コード例 #19
0
ファイル: boot_hostdev_test.py プロジェクト: wuyeliang/vdsm
 def _run_hook(self, domxml, boot_hostdev):
     with temporaryPath(data=domxml.encode('utf-8')) as temp_path:
         env = self._setup_env(temp_path, boot_hostdev)
         rc, out, err = commands.execCmd(
             [sys.executable, _HOOK_PATH], env=env)
         with io.open(temp_path, 'r') as outxml:
             outxml = outxml.read()
         return outxml, rc, out, err
コード例 #20
0
ファイル: check_test.py プロジェクト: gobindadas/vdsm
 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)
コード例 #21
0
ファイル: storage_check_test.py プロジェクト: yingyun001/vdsm
 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)
コード例 #22
0
ファイル: hooking_test.py プロジェクト: wuyeliang/vdsm
    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)
コード例 #23
0
ファイル: fileUtilTests.py プロジェクト: kanalun/vdsm
 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)
コード例 #24
0
 def test_ignore_file_body(self):
     data = (b"#REVISION: 1\n"
             b"#PRIVATE: YES\n"
             b"REVISION: 2\n"
             b"PRIVATE: NO\n")
     with temporaryPath(data=data) as path:
         md = confmeta.read_metadata(path)
         self.assertEqual(md.revision, 1)
         self.assertEqual(md.private, True)
コード例 #25
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:
         # two nested withs to be py2.6 friendly.
         with fileUtils.open_ex(srcPath, "dr") as f:
             self.assertEquals(f.read(), data)
コード例 #26
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:
         with 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)
コード例 #27
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)
コード例 #28
0
ファイル: qemuimg_test.py プロジェクト: chaodongqu/vdsm
 def test_preallocation_off(self, preallocation):
     virtual_size = 10 * 1024**2
     with temporaryPath() as image:
         op = qemuimg.create(
             image,
             size=virtual_size,
             format=qemuimg.FORMAT.RAW,
             preallocation=preallocation)
         op.run()
         check_raw_sparse_image(image, virtual_size)
コード例 #29
0
 def _hook_env(self, domain_xml, **env_vars):
     with _setup_os_environ_vars(env_vars):
         with temporaryPath(data=domain_xml.encode('utf-8')) as path:
             os.environ['_hook_domxml'] = path
             try:
                 yield
             finally:
                 os.environ.pop('_hook_domxml')
                 with open(path) as res:
                     self.out_xml = res.read()
コード例 #30
0
ファイル: qemuimg_test.py プロジェクト: nirs/vdsm
 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
コード例 #31
0
ファイル: qemuimg_test.py プロジェクト: olegtikhonov/vdsm
 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
         self.assertEqual(allocated, allocated_bytes)
コード例 #32
0
 def test_order_does_not_matter(self):
     data = (b"# A comment\n"
             b"#PRIVATE: NO\n"
             b"# Another comment\n"
             b"#REVISION: 1\n"
             b"# Last comment\n"
             b"Actual file data...")
     with temporaryPath(data=data) as path:
         md = confmeta.read_metadata(path)
         self.assertEqual(md.revision, 1)
         self.assertEqual(md.private, False)
コード例 #33
0
ファイル: storage_check_test.py プロジェクト: yingyun001/vdsm
 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)
コード例 #34
0
ファイル: check_test.py プロジェクト: vjuranek/vdsm
 def test_taskset_missing(self, monkeypatch):
     monkeypatch.setattr(constants, "EXT_TASKSET", "/no/such/executable")
     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]
         with pytest.raises(exception.MiscFileReadException):
             result.delay()
コード例 #35
0
ファイル: cpu_profile_test.py プロジェクト: wuyeliang/vdsm
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
コード例 #36
0
ファイル: check_test.py プロジェクト: gobindadas/vdsm
 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)
コード例 #37
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)
コード例 #38
0
ファイル: check_test.py プロジェクト: dong-df/vdsm
 def test_path_ok_leak(self):
     fds_before = set(os.listdir("/proc/self/fd"))
     self.checks = 10
     with temporaryPath(data=b"blah") as path:
         checker = check.DirectioChecker(self.loop,
                                         path,
                                         self.complete,
                                         interval=0.1)
         checker.start()
         self.loop.run_forever()
         pprint.pprint(self.results)
     fds_after = set(os.listdir("/proc/self/fd"))
     assert fds_before == fds_after
コード例 #39
0
ファイル: fileUtilTests.py プロジェクト: yingyun001/vdsm
    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)
コード例 #40
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)
コード例 #41
0
ファイル: check_test.py プロジェクト: gobindadas/vdsm
 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()
コード例 #42
0
ファイル: storage_check_test.py プロジェクト: yingyun001/vdsm
 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()
コード例 #43
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])
コード例 #44
0
ファイル: API_test.py プロジェクト: EdDev/vdsm
    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])
コード例 #45
0
ファイル: fallocate_test.py プロジェクト: nirs/vdsm
    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)
コード例 #46
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)
コード例 #47
0
ファイル: API_test.py プロジェクト: EdDev/vdsm
    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)
コード例 #48
0
ファイル: fallocate_test.py プロジェクト: xin49/vdsm
    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)
コード例 #49
0
ファイル: check_test.py プロジェクト: nirs/vdsm
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
コード例 #50
0
ファイル: virtTests.py プロジェクト: nickxiao/vdsm
    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"])
コード例 #51
0
ファイル: mount_test.py プロジェクト: nirs/vdsm
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
コード例 #52
0
ファイル: virtTests.py プロジェクト: yingyun001/vdsm
    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'])
コード例 #53
0
ファイル: fileUtilTests.py プロジェクト: kanalun/vdsm
 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:])
コード例 #54
0
ファイル: clientif_test.py プロジェクト: EdDev/vdsm
 def testStringAsDrive(self):
     with temporaryPath() as f:
         volPath = self.cif.prepareVolumePath(f)
         self.assertEqual(volPath, f)
コード例 #55
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)
コード例 #56
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())
コード例 #57
0
ファイル: fileUtilTests.py プロジェクト: yingyun001/vdsm
 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)