From b22d7bee0b787b6e7906d882f97f49f82b34bdae Mon Sep 17 00:00:00 2001 From: Thomas Adamcik Date: Fri, 22 Nov 2013 07:13:36 +0100 Subject: [PATCH] utils: Add mkdir and content options to get_or_create_file This lets callers control is parent directories are created, and set the default content of the file. --- mopidy/utils/path.py | 9 ++++++--- tests/utils/path_test.py | 16 ++++++++++++++-- 2 files changed, 20 insertions(+), 5 deletions(-) diff --git a/mopidy/utils/path.py b/mopidy/utils/path.py index c5aa6e45..32dcb721 100644 --- a/mopidy/utils/path.py +++ b/mopidy/utils/path.py @@ -37,14 +37,17 @@ def get_or_create_dir(dir_path): return dir_path -def get_or_create_file(file_path): +def get_or_create_file(file_path, mkdir=True, content=None): if not isinstance(file_path, bytes): raise ValueError('Path is not a bytestring.') file_path = expand_path(file_path) - get_or_create_dir(os.path.dirname(file_path)) + if mkdir: + get_or_create_dir(os.path.dirname(file_path)) if not os.path.isfile(file_path): logger.info('Creating file %s', file_path) - open(file_path, 'w').close() + with open(file_path, 'w') as fh: + if content: + fh.write(content) return file_path diff --git a/tests/utils/path_test.py b/tests/utils/path_test.py index ed9f8044..a3892b8a 100644 --- a/tests/utils/path_test.py +++ b/tests/utils/path_test.py @@ -102,17 +102,29 @@ class GetOrCreateFileTest(unittest.TestCase): def test_create_file_with_name_of_existing_dir_throws_ioerror(self): conflicting_dir = os.path.join(self.parent) - self.assertRaises(IOError, path.get_or_create_file, conflicting_dir) + with self.assertRaises(IOError): + path.get_or_create_file(conflicting_dir) def test_create_dir_with_unicode(self): with self.assertRaises(ValueError): file_path = unicode(os.path.join(self.parent, b'test')) path.get_or_create_file(file_path) - def test_create_dir_with_none(self): + def test_create_file_with_none(self): with self.assertRaises(ValueError): path.get_or_create_file(None) + def test_create_dir_without_mkdir(self): + file_path = os.path.join(self.parent, b'foo', b'bar') + with self.assertRaises(IOError): + path.get_or_create_file(file_path, mkdir=False) + + def test_create_dir_with_defualt_content(self): + file_path = os.path.join(self.parent, b'test') + created = path.get_or_create_file(file_path, content=b'foobar') + with open(created) as fh: + self.assertEqual(fh.read(), b'foobar') + class PathToFileURITest(unittest.TestCase): def test_simple_path(self):