Update prebuilt.py to handle files not existing. Add a unittest to test the case

TBR=sosa

BUG=NA
TEST=Unittest

Review URL: http://codereview.chromium.org/6261013
This commit is contained in:
Scott Zawalski 2011-01-18 20:33:32 -08:00
parent e90029493e
commit 7bac5ab46f
2 changed files with 21 additions and 3 deletions

View File

@ -92,7 +92,10 @@ def UpdateLocalFile(filename, value, key='PORTAGE_BINHOST'):
value: Value to write with the key.
key: The variable key to update. (Default: PORTAGE_BINHOST)
"""
file_fh = open(filename)
if os.path.exists(filename):
file_fh = open(filename)
else:
file_fh = open(filename, 'w+')
file_lines = []
found = False
keyval_str = '%(key)s=%(value)s'

View File

@ -45,9 +45,12 @@ class TestUpdateFile(unittest.TestCase):
def tearDown(self):
os.remove(self.version_file)
def _read_version_file(self):
def _read_version_file(self, version_file=None):
"""Read the contents of self.version_file and return as a list."""
version_fh = open(self.version_file)
if not version_file:
version_file = self.version_file
version_fh = open(version_file)
try:
return [line.strip() for line in version_fh.readlines()]
finally:
@ -86,6 +89,18 @@ class TestUpdateFile(unittest.TestCase):
prebuilt.UpdateLocalFile(self.version_file, new_val)
self._verify_key_pair(key, new_val)
def testUpdateNonExistentFile(self):
key = 'PORTAGE_BINHOST'
value = '1234567'
non_existent_file = tempfile.mktemp()
try:
prebuilt.UpdateLocalFile(non_existent_file, value)
file_contents = self._read_version_file(non_existent_file)
self.assertEqual(file_contents, ['%s=%s' % (key, value)])
finally:
if os.path.exists(non_existent_file):
os.remove(non_existent_file)
class TestPrebuiltFilters(unittest.TestCase):