path: Support unicode content when creating file

This commit is contained in:
Stein Magnus Jodal 2014-12-23 22:11:11 +01:00
parent 532905bd74
commit aa3b8ab5f8
2 changed files with 13 additions and 5 deletions

View File

@ -44,12 +44,14 @@ 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)
if isinstance(content, unicode):
content = content.encode('utf-8')
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)
with open(file_path, 'w') as fh:
if content:
with open(file_path, 'wb') as fh:
if content is not None:
fh.write(content)
return file_path

View File

@ -105,12 +105,12 @@ class GetOrCreateFileTest(unittest.TestCase):
with self.assertRaises(IOError):
path.get_or_create_file(conflicting_dir)
def test_create_dir_with_unicode(self):
def test_create_dir_with_unicode_filename_throws_value_error(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_file_with_none(self):
def test_create_file_with_none_filename_throws_value_error(self):
with self.assertRaises(ValueError):
path.get_or_create_file(None)
@ -119,12 +119,18 @@ class GetOrCreateFileTest(unittest.TestCase):
with self.assertRaises(IOError):
path.get_or_create_file(file_path, mkdir=False)
def test_create_dir_with_default_content(self):
def test_create_dir_with_bytes_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')
def test_create_dir_with_unicode_content(self):
file_path = os.path.join(self.parent, b'test')
created = path.get_or_create_file(file_path, content='foobaræøå')
with open(created) as fh:
self.assertEqual(fh.read(), b'foobaræøå')
class PathToFileURITest(unittest.TestCase):
def test_simple_path(self):