From 7bac5ab46f929018f406c53f5371fc5fd28dcf36 Mon Sep 17 00:00:00 2001 From: Scott Zawalski Date: Tue, 18 Jan 2011 20:33:32 -0800 Subject: [PATCH] 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 --- prebuilt.py | 5 ++++- prebuilt_unittest.py | 19 +++++++++++++++++-- 2 files changed, 21 insertions(+), 3 deletions(-) diff --git a/prebuilt.py b/prebuilt.py index 01f3d331ec..799253c8cf 100755 --- a/prebuilt.py +++ b/prebuilt.py @@ -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' diff --git a/prebuilt_unittest.py b/prebuilt_unittest.py index 1e0f2ea385..d3291333f0 100755 --- a/prebuilt_unittest.py +++ b/prebuilt_unittest.py @@ -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):