Skip to content

Commit dd606d1

Browse files
committed
Clean up file I/O operations
1 parent be0597a commit dd606d1

11 files changed

Lines changed: 120 additions & 116 deletions

File tree

src/clusterfuzz/_internal/bot/tasks/setup.py

Lines changed: 25 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -841,11 +841,14 @@ def archive_testcase_and_dependencies_in_gcs(resource_list, testcase_path: str,
841841

842842
logs.info(f'Testcase and related files :\n{resource_list}')
843843

844+
upload_file_path = testcase_path
844845
if len(resource_list) <= 1:
845846
# If this does not have any resources, just save the testcase.
846847
# TODO(flowerhack): Update this when we teach CF how to download testcases.
847848
try:
848-
file_handle = open(testcase_path, 'rb')
849+
with open(testcase_path, 'rb') as _:
850+
# Verify file can be opened.
851+
pass
849852
except OSError:
850853
logs.error(f'Unable to open testcase {testcase_path}.')
851854
return None, None, None
@@ -879,31 +882,37 @@ def archive_testcase_and_dependencies_in_gcs(resource_list, testcase_path: str,
879882

880883
# Create the archive.
881884
zip_path = os.path.join(environment.get_value('INPUT_DIR'), zip_filename)
882-
zip_file = zipfile.ZipFile(zip_path, 'w')
883-
for file_name in resource_list:
884-
if os.path.exists(file_name):
885-
relative_filename = file_name[base_len:]
886-
zip_file.write(file_name, relative_filename, zipfile.ZIP_DEFLATED)
887-
zip_file.close()
885+
with zipfile.ZipFile(zip_path, 'w') as zip_file:
886+
for file_name in resource_list:
887+
if os.path.exists(file_name):
888+
relative_filename = file_name[base_len:]
889+
zip_file.write(file_name, relative_filename, zipfile.ZIP_DEFLATED)
888890

889891
try:
890-
file_handle = open(zip_path, 'rb')
892+
with open(zip_path, 'rb') as _:
893+
# Verify file can be opened.
894+
pass
895+
upload_file_path = zip_path
891896
except OSError:
892897
logs.error(f'Unable to open testcase archive {zip_path}.')
893898
return None, None, None
899+
finally:
900+
if zip_path:
901+
shell.remove_file(zip_path)
894902

895903
archived = True
896904
absolute_filename = testcase_path[base_len:]
897905

898-
if not storage.upload_signed_url(file_handle, upload_url):
899-
logs.error('Failed to upload testcase.')
900-
return None, None, None
901-
902-
file_handle.close()
906+
try:
907+
with open(upload_file_path, 'rb') as file_handle:
908+
if not storage.upload_signed_url(file_handle, upload_url):
909+
logs.error('Failed to upload testcase.')
910+
return None, None, None
903911

904-
# Don't need the archive after writing testcase to blobstore.
905-
if zip_path:
906-
shell.remove_file(zip_path)
912+
finally:
913+
# Don't need the archive after writing testcase to blobstore.
914+
if zip_path:
915+
shell.remove_file(zip_path)
907916

908917
return archived, absolute_filename, zip_filename
909918

src/clusterfuzz/_internal/bot/tasks/unpack_task.py

Lines changed: 2 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -89,9 +89,8 @@ def execute_task(metadata_id, job_type):
8989
continue
9090

9191
try:
92-
file_handle = open(absolute_file_path, 'rb')
93-
blob_key = blobs.write_blob(file_handle)
94-
file_handle.close()
92+
with open(absolute_file_path, 'rb') as file_handle:
93+
blob_key = blobs.write_blob(file_handle)
9594
except:
9695
blob_key = None
9796

src/clusterfuzz/_internal/bot/tasks/utasks/minimize_task.py

Lines changed: 31 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -1028,45 +1028,42 @@ def store_minimized_testcase(
10281028

10291029
# Prepare the file.
10301030
zip_path = None
1031+
testcase_filepath = None
10311032
if testcase.archive_state:
10321033
if len(file_list) > 1:
10331034
testcase.archive_state |= data_types.ArchiveStatus.MINIMIZED
10341035
minimize_task_output.archive_state = testcase.archive_state
10351036
zip_path = os.path.join(
10361037
environment.get_value('INPUT_DIR'), '%d.zip' % testcase.key.id())
1037-
zip_file = zipfile.ZipFile(zip_path, 'w')
1038-
count = 0
1039-
filtered_file_list = []
1040-
for file_name in file_list:
1041-
absolute_filename = os.path.join(base_directory, file_name)
1042-
is_file = os.path.isfile(absolute_filename)
1043-
if file_to_run_data and is_file and os.path.getsize(
1044-
absolute_filename) == 0 and (os.path.basename(
1045-
absolute_filename).encode('utf-8') not in file_to_run_data):
1046-
continue
1047-
if not os.path.exists(absolute_filename):
1048-
continue
1049-
zip_file.write(absolute_filename, file_name, zipfile.ZIP_DEFLATED)
1050-
if is_file:
1051-
count += 1
1052-
filtered_file_list.append(absolute_filename)
1053-
1054-
zip_file.close()
1038+
with zipfile.ZipFile(zip_path, 'w') as zip_file:
1039+
count = 0
1040+
filtered_file_list = []
1041+
for file_name in file_list:
1042+
absolute_filename = os.path.join(base_directory, file_name)
1043+
is_file = os.path.isfile(absolute_filename)
1044+
if file_to_run_data and is_file and os.path.getsize(
1045+
absolute_filename) == 0 and (os.path.basename(
1046+
absolute_filename).encode('utf-8') not in file_to_run_data):
1047+
continue
1048+
if not os.path.exists(absolute_filename):
1049+
continue
1050+
zip_file.write(absolute_filename, file_name, zipfile.ZIP_DEFLATED)
1051+
if is_file:
1052+
count += 1
1053+
filtered_file_list.append(absolute_filename)
1054+
10551055
try:
10561056
if count > 1:
1057-
file_handle = open(zip_path, 'rb')
1057+
testcase_filepath = zip_path
10581058
else:
10591059
if not filtered_file_list:
10601060
# We minimized everything. The only thing needed to reproduce is the
10611061
# interaction gesture.
1062-
file_path = file_list[0]
1063-
file_handle = open(file_path, 'wb')
1064-
file_handle.close()
1062+
testcase_filepath = file_list[0]
10651063
else:
1066-
file_path = filtered_file_list[0]
1067-
file_handle = open(file_path, 'rb')
1068-
testcase.absolute_path = os.path.join(base_directory,
1069-
os.path.basename(file_path))
1064+
testcase_filepath = filtered_file_list[0]
1065+
testcase.absolute_path = os.path.join(
1066+
base_directory, os.path.basename(testcase_filepath))
10701067
minimize_task_output.absolute_path = testcase.absolute_path
10711068
testcase.archive_state &= ~data_types.ArchiveStatus.MINIMIZED
10721069
minimize_task_output.archive_state = testcase.archive_state
@@ -1075,20 +1072,20 @@ def store_minimized_testcase(
10751072
return
10761073
else:
10771074
absolute_filename = os.path.join(base_directory, file_list[0])
1078-
file_handle = open(absolute_filename, 'rb')
1075+
testcase_filepath = absolute_filename
10791076
testcase.archive_state &= ~data_types.ArchiveStatus.MINIMIZED
10801077
minimize_task_output.archive_state = testcase.archive_state
10811078
else:
1082-
file_handle = open(file_list[0], 'rb')
1079+
testcase_filepath = file_list[0]
10831080
testcase.archive_state &= ~data_types.ArchiveStatus.MINIMIZED
10841081
minimize_task_output.archive_state = testcase.archive_state
10851082

10861083
# Store the testcase.
1087-
data = file_handle.read()
1088-
storage.upload_signed_url(data, minimize_task_input.testcase_upload_url)
1089-
minimized_keys = minimize_task_input.testcase_blob_name
1090-
file_handle.close()
1084+
with open(testcase_filepath, 'rb') as file_handle:
1085+
data = file_handle.read()
1086+
storage.upload_signed_url(data, minimize_task_input.testcase_upload_url)
10911087

1088+
minimized_keys = minimize_task_input.testcase_blob_name
10921089
testcase.minimized_keys = minimized_keys
10931090
minimize_task_output.minimized_keys = minimized_keys
10941091

@@ -1318,9 +1315,8 @@ def combine_tokens(tokens):
13181315
return b''
13191316

13201317
# TODO(mbarbella): Allow token combining functions to write files directly.
1321-
handle = open(combined_file_path, 'rb')
1322-
result = handle.read()
1323-
handle.close()
1318+
with open(combined_file_path, 'rb') as handle:
1319+
result = handle.read()
13241320

13251321
shell.remove_file(combined_file_path)
13261322
return result

src/clusterfuzz/_internal/platforms/android/device.py

Lines changed: 14 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -214,22 +214,20 @@ def configure_system_build_properties():
214214

215215
# Write new build.prop.
216216
new_build_prop_path = os.path.join(bot_tmp_directory, 'new.prop')
217-
old_build_prop_file_content = open(old_build_prop_path)
218-
new_build_prop_file_content = open(new_build_prop_path, 'w')
219-
new_content_notification = '### CHANGED OR ADDED PROPERTIES ###'
220-
for line in old_build_prop_file_content:
221-
property_name = line.split('=')[0].strip()
222-
if property_name in BUILD_PROPERTIES:
223-
continue
224-
if new_content_notification in line:
225-
continue
226-
new_build_prop_file_content.write(line)
227-
228-
new_build_prop_file_content.write(new_content_notification + '\n')
229-
for flag, value in BUILD_PROPERTIES.items():
230-
new_build_prop_file_content.write('%s=%s\n' % (flag, value))
231-
old_build_prop_file_content.close()
232-
new_build_prop_file_content.close()
217+
with open(old_build_prop_path) as old_build_prop_file_content, \
218+
open(new_build_prop_path, 'w') as new_build_prop_file_content:
219+
new_content_notification = '### CHANGED OR ADDED PROPERTIES ###'
220+
for line in old_build_prop_file_content:
221+
property_name = line.split('=')[0].strip()
222+
if property_name in BUILD_PROPERTIES:
223+
continue
224+
if new_content_notification in line:
225+
continue
226+
new_build_prop_file_content.write(line)
227+
228+
new_build_prop_file_content.write(new_content_notification + '\n')
229+
for flag, value in BUILD_PROPERTIES.items():
230+
new_build_prop_file_content.write('%s=%s\n' % (flag, value))
233231

234232
# Keep verified boot disabled for M and higher releases. This makes it easy
235233
# to modify system's app_process to load asan libraries.

src/clusterfuzz/_internal/tests/core/base/utils_test.py

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -618,8 +618,9 @@ def test_file_exists_valid_content(self):
618618

619619
def test_file_exists_empty_content(self):
620620
"""Test reading empty manifest file."""
621-
f = open(self.test_path, 'w')
622-
f.close()
621+
with open(self.test_path, 'w') as _:
622+
# Opens file with 'w' to clear it.
623+
pass
623624
self.assertEqual(utils.current_source_version(), '')
624625

625626
def test_file_exists_invalid_content(self):

src/clusterfuzz/_internal/tests/core/bot/minimizer/base_minimizer_tester.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -24,7 +24,8 @@ def setUp(self):
2424

2525
def _mock_test_function(self, data_file):
2626
"""Mock test function to reduce time minimizer takes and simplify tests."""
27-
data = open(data_file, 'rb').read()
27+
with open(data_file, 'rb') as f:
28+
data = f.read()
2829
if b'error' in data:
2930
return False
3031
return True

src/clusterfuzz/_internal/tests/core/bot/minimizer/unicode_minimizer_test.py

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -50,7 +50,8 @@ def setUp(self):
5050
self._mock_test_function)
5151

5252
def _mock_test_function(self, data_file):
53-
data = open(data_file, 'rb').read()
53+
with open(data_file, 'rb') as f:
54+
data = f.read()
5455
if data in self.crash_programs:
5556
return False
5657
if data in self.no_crash_programs:

src/clusterfuzz/_internal/tests/core/bot/tasks/update_task_test.py

Lines changed: 13 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -248,23 +248,23 @@ def test_all_files_are_correctly_unpacked(self):
248248
zipfile_path = os.path.join(self._make_temp_dir(), 'linux.zip')
249249
storage.copy_file_from('gs://clusterfuzz-deployment/linux-3.zip',
250250
zipfile_path)
251-
archive = zipfile.ZipFile(zipfile_path)
252-
for file in archive.namelist():
253-
if os.path.basename(file) == 'adb':
254-
continue
255-
self.assertTrue(os.path.exists(os.path.join(self.temp_directory, file)))
251+
with zipfile.ZipFile(zipfile_path) as archive:
252+
for file in archive.namelist():
253+
if os.path.basename(file) == 'adb':
254+
continue
255+
self.assertTrue(os.path.exists(os.path.join(self.temp_directory, file)))
256256

257257
def test_archive_execute_permission_is_respected(self):
258258
"""Tests that the exectuable bit is correctly propagated to source files."""
259259
update_task.update_source_code()
260260
zipfile_path = os.path.join(self._make_temp_dir(), 'linux.zip')
261261
storage.copy_file_from('gs://clusterfuzz-deployment/linux-3.zip',
262262
zipfile_path)
263-
archive = zipfile.ZipFile(zipfile_path)
264-
for member in archive.infolist():
265-
if os.path.basename(member.filename) == 'adb':
266-
continue
267-
mode = (member.external_attr >> 16) & 0o7777
268-
filepath = os.path.join(self.temp_directory, member.filename)
269-
if mode & 0o100:
270-
self.assertTrue(os.access(filepath, os.X_OK))
263+
with zipfile.ZipFile(zipfile_path) as archive:
264+
for member in archive.infolist():
265+
if os.path.basename(member.filename) == 'adb':
266+
continue
267+
mode = (member.external_attr >> 16) & 0o7777
268+
filepath = os.path.join(self.temp_directory, member.filename)
269+
if mode & 0o100:
270+
self.assertTrue(os.access(filepath, os.X_OK))

src/clusterfuzz/_internal/tests/core/bot/tasks/utasks/minimize_task_test.py

Lines changed: 4 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -399,7 +399,8 @@ def test_irreducible_input(self):
399399

400400
def mock_test_function_unicode_dependent(data_file):
401401
"""If crash -> False, otherwise -> True."""
402-
data = open(data_file, 'rb').read()
402+
with open(data_file, 'rb') as f:
403+
data = f.read()
403404

404405
if data == b'consol\\u0065.log(42);':
405406
return False
@@ -417,7 +418,8 @@ def test_reducible_input(self):
417418

418419
def mock_test_function_unicode_independent(data_file):
419420
"""If crash -> False, otherwise -> True."""
420-
data = open(data_file, 'rb').read()
421+
with open(data_file, 'rb') as f:
422+
data = f.read()
421423

422424
if data in (b'consol\\u0065.log(42);', b'console.log(42);'):
423425
return False

src/local/butler/common.py

Lines changed: 5 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -227,13 +227,12 @@ def _install_chromedriver():
227227
constants.CHROMEDRIVER_DOWNLOAD_PATTERN.format(
228228
version=version, archive_name=archive_name))
229229
archive_io = io.BytesIO(archive_request.read())
230-
chromedriver_archive = zipfile.ZipFile(archive_io)
230+
with zipfile.ZipFile(archive_io) as chromedriver_archive:
231+
chromedriver_path = get_chromedriver_path()
232+
output_directory = os.path.dirname(chromedriver_path)
233+
chromedriver_binary = os.path.basename(chromedriver_path)
231234

232-
chromedriver_path = get_chromedriver_path()
233-
output_directory = os.path.dirname(chromedriver_path)
234-
chromedriver_binary = os.path.basename(chromedriver_path)
235-
236-
chromedriver_archive.extract(chromedriver_binary, output_directory)
235+
chromedriver_archive.extract(chromedriver_binary, output_directory)
237236
os.chmod(chromedriver_path, 0o750)
238237
print(f'Installed chromedriver at: {chromedriver_path}')
239238

0 commit comments

Comments
 (0)