Revision 6e797216
b/lib/utils.py | ||
---|---|---|
285 | 285 |
raise |
286 | 286 |
|
287 | 287 |
|
288 |
def RenameFile(old, new, mkdir=False, mkdir_mode=0750): |
|
289 |
"""Renames a file. |
|
290 |
|
|
291 |
@type old: string |
|
292 |
@param old: Original path |
|
293 |
@type new: string |
|
294 |
@param new: New path |
|
295 |
@type mkdir: bool |
|
296 |
@param mkdir: Whether to create target directory if it doesn't exist |
|
297 |
@type mkdir_mode: int |
|
298 |
@param mkdir_mode: Mode for newly created directories |
|
299 |
|
|
300 |
""" |
|
301 |
try: |
|
302 |
return os.rename(old, new) |
|
303 |
except OSError, err: |
|
304 |
# In at least one use case of this function, the job queue, directory |
|
305 |
# creation is very rare. Checking for the directory before renaming is not |
|
306 |
# as efficient. |
|
307 |
if mkdir and err.errno == errno.ENOENT: |
|
308 |
# Create directory and try again |
|
309 |
os.makedirs(os.path.dirname(new), mkdir_mode) |
|
310 |
return os.rename(old, new) |
|
311 |
raise |
|
312 |
|
|
313 |
|
|
288 | 314 |
def _FingerprintFile(filename): |
289 | 315 |
"""Compute the fingerprint of a file. |
290 | 316 |
|
b/test/ganeti.utils_unittest.py | ||
---|---|---|
277 | 277 |
self.fail("File '%s' not removed" % symlink) |
278 | 278 |
|
279 | 279 |
|
280 |
class TestRename(unittest.TestCase): |
|
281 |
"""Test case for RenameFile""" |
|
282 |
|
|
283 |
def setUp(self): |
|
284 |
"""Create a temporary directory""" |
|
285 |
self.tmpdir = tempfile.mkdtemp() |
|
286 |
self.tmpfile = os.path.join(self.tmpdir, "test1") |
|
287 |
|
|
288 |
# Touch the file |
|
289 |
open(self.tmpfile, "w").close() |
|
290 |
|
|
291 |
def tearDown(self): |
|
292 |
"""Remove temporary directory""" |
|
293 |
shutil.rmtree(self.tmpdir) |
|
294 |
|
|
295 |
def testSimpleRename1(self): |
|
296 |
"""Simple rename 1""" |
|
297 |
utils.RenameFile(self.tmpfile, os.path.join(self.tmpdir, "xyz")) |
|
298 |
|
|
299 |
def testSimpleRename2(self): |
|
300 |
"""Simple rename 2""" |
|
301 |
utils.RenameFile(self.tmpfile, os.path.join(self.tmpdir, "xyz"), |
|
302 |
mkdir=True) |
|
303 |
|
|
304 |
def testRenameMkdir(self): |
|
305 |
"""Rename with mkdir""" |
|
306 |
utils.RenameFile(self.tmpfile, os.path.join(self.tmpdir, "test/xyz"), |
|
307 |
mkdir=True) |
|
308 |
|
|
309 |
|
|
280 | 310 |
class TestCheckdict(unittest.TestCase): |
281 | 311 |
"""Test case for the CheckDict function""" |
282 | 312 |
|
Also available in: Unified diff