diff --git a/lib/utils.py b/lib/utils.py index 1ef35cb3382753b98a4bd77d7e939493af93c0b7..a5ec895adf8c30401589ee6320d2a87bbfcfbd04 100644 --- a/lib/utils.py +++ b/lib/utils.py @@ -1715,11 +1715,13 @@ def OwnIpAddress(address): source=constants.LOCALHOST_IP_ADDRESS) -def ListVisibleFiles(path): +def ListVisibleFiles(path, sort=True): """Returns a list of visible files in a directory. @type path: str @param path: the directory to enumerate + @type sort: boolean + @param sort: whether to provide a sorted output @rtype: list @return: the list of all files not starting with a dot @raise ProgrammerError: if L{path} is not an absolue and normalized path @@ -1729,7 +1731,8 @@ def ListVisibleFiles(path): raise errors.ProgrammerError("Path passed to ListVisibleFiles is not" " absolute/normalized: '%s'" % path) files = [i for i in os.listdir(path) if not i.startswith(".")] - files.sort() + if sort: + files.sort() return files diff --git a/test/ganeti.utils_unittest.py b/test/ganeti.utils_unittest.py index 68ef826727b036ca0718b1e7d05a729ef4ff31a0..691b5d03f516913c58d342f2a732f1c2b5fee6b9 100755 --- a/test/ganeti.utils_unittest.py +++ b/test/ganeti.utils_unittest.py @@ -1334,22 +1334,15 @@ class TestListVisibleFiles(unittest.TestCase): def tearDown(self): shutil.rmtree(self.path) - def _test(self, files, expected): - # Sort a copy - expected = expected[:] - expected.sort() - + def _CreateFiles(self, files): for name in files: - f = open(os.path.join(self.path, name), 'w') - try: - f.write("Test\n") - finally: - f.close() + utils.WriteFile(os.path.join(self.path, name), data="test") + def _test(self, files, expected): + self._CreateFiles(files) found = ListVisibleFiles(self.path) - found.sort() - - self.assertEqual(found, expected) + # by default ListVisibleFiles sorts its output + self.assertEqual(found, sorted(expected)) def testAllVisible(self): files = ["a", "b", "c"] @@ -1366,6 +1359,20 @@ class TestListVisibleFiles(unittest.TestCase): expected = ["a", "b"] self._test(files, expected) + def testForceSort(self): + files = ["c", "b", "a"] + self._CreateFiles(files) + found = ListVisibleFiles(self.path, sort=True) + self.assertEqual(found, sorted(files)) + + def testForceNonSort(self): + files = ["c", "b", "a"] + self._CreateFiles(files) + found = ListVisibleFiles(self.path, sort=False) + # We can't actually check that they weren't sorted, because they might come + # out sorted by chance + self.assertEqual(set(found), set(files)) + def testNonAbsolutePath(self): self.failUnlessRaises(errors.ProgrammerError, ListVisibleFiles, "abc")