Skip to content

Commit

Permalink
simplify find_backup_name_candidate & add test
Browse files Browse the repository at this point in the history
  • Loading branch information
boegel committed Aug 17, 2017
1 parent ab9addb commit cd4c395
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 7 deletions.
13 changes: 6 additions & 7 deletions easybuild/tools/filetools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1163,16 +1163,15 @@ def rmtree2(path, n=3):
else:
_log.info("Path %s successfully removed." % path)


def find_backup_name_candidate(src_file):
"""Returns a non-existing file to be used as destination for rotating backups"""
"""Returns a non-existing file to be used as destination for backup files"""
dst_file = src_file

if os.path.exists(src_file):
i = 0
dst_file = "%s_%d" % (src_file, i)
while os.path.exists(dst_file):
i += 1
dst_file = "%s_%d" % (src_file, i)
i = 0
while os.path.exists(dst_file):
dst_file = '%s_%d' % (src_file, i)
i += 1

return dst_file

Expand Down
22 changes: 22 additions & 0 deletions test/framework/filetools.py
Original file line number Diff line number Diff line change
Expand Up @@ -1355,6 +1355,28 @@ def test_move_file(self):
self.assertEqual(ft.read_file(test_file), 'test123')
self.assertFalse(os.path.exists(new_test_file))

def test_find_backup_name_candidate(self):
"""Test find_backup_name_candidate"""
test_file = os.path.join(self.test_prefix, 'test.txt')
ft.write_file(test_file, 'foo')

res = ft.find_backup_name_candidate(test_file)
self.assertTrue(os.path.samefile(os.path.dirname(res), self.test_prefix))
self.assertEqual(os.path.basename(res), 'test.txt_0')

ft.write_file(os.path.join(self.test_prefix, 'test.txt_0'), '')
res = ft.find_backup_name_candidate(test_file)
self.assertTrue(os.path.samefile(os.path.dirname(res), self.test_prefix))
self.assertEqual(os.path.basename(res), 'test.txt_1')

# generate backup files until test.txt_122
for idx in range(1, 123):
ft.write_file(os.path.join(self.test_prefix, 'test.txt_%d' % idx), '')

res = ft.find_backup_name_candidate(test_file)
self.assertTrue(os.path.samefile(os.path.dirname(res), self.test_prefix))
self.assertEqual(os.path.basename(res), 'test.txt_123')


def suite():
""" returns all the testcases in this module """
Expand Down

0 comments on commit cd4c395

Please sign in to comment.