From f11c6bcab87ee8927e23a23d2300900a0922616d Mon Sep 17 00:00:00 2001 From: laszlocsomor Date: Thu, 5 Jul 2018 01:58:06 -0700 Subject: python tools: ensure files are closed Use the "with" statement to open files in various Python scripts used by Bazel, to ensure these files are closed eagerly. See https://github.com/bazelbuild/bazel/issues/5512 RELNOTES: none PiperOrigin-RevId: 203346678 --- src/test/py/bazel/bazel_windows_cpp_test.py | 12 ++++++------ src/test/py/bazel/cc_import_test.py | 7 +++---- src/test/shell/bazel/testing_server.py | 4 ++-- 3 files changed, 11 insertions(+), 12 deletions(-) (limited to 'src/test') diff --git a/src/test/py/bazel/bazel_windows_cpp_test.py b/src/test/py/bazel/bazel_windows_cpp_test.py index 3d21929205..40fe50905c 100644 --- a/src/test/py/bazel/bazel_windows_cpp_test.py +++ b/src/test/py/bazel/bazel_windows_cpp_test.py @@ -436,14 +436,14 @@ class BazelWindowsCppTest(test_base.TestBase): self.AssertFileContentContains(def_file, 'hello_C') def AssertFileContentContains(self, file_path, entry): - f = open(file_path, 'r') - if entry not in f.read(): - self.fail('File "%s" does not contain "%s"' % (file_path, entry)) + with open(file_path, 'r') as f: + if entry not in f.read(): + self.fail('File "%s" does not contain "%s"' % (file_path, entry)) def AssertFileContentNotContains(self, file_path, entry): - f = open(file_path, 'r') - if entry in f.read(): - self.fail('File "%s" does contain "%s"' % (file_path, entry)) + with open(file_path, 'r') as f: + if entry in f.read(): + self.fail('File "%s" does contain "%s"' % (file_path, entry)) def testWinDefFileAttribute(self): self.ScratchFile('WORKSPACE') diff --git a/src/test/py/bazel/cc_import_test.py b/src/test/py/bazel/cc_import_test.py index 99ab086a28..b20479904d 100644 --- a/src/test/py/bazel/cc_import_test.py +++ b/src/test/py/bazel/cc_import_test.py @@ -247,10 +247,9 @@ class CcImportTest(test_base.TestBase): ''.join(stderr)) def AssertFileContentContains(self, file_path, entry): - f = open(file_path, 'r') - if entry not in f.read(): - self.fail('File "%s" does not contain "%s"' % (file_path, entry)) - f.close() + with open(file_path, 'r') as f: + if entry not in f.read(): + self.fail('File "%s" does not contain "%s"' % (file_path, entry)) if __name__ == '__main__': diff --git a/src/test/shell/bazel/testing_server.py b/src/test/shell/bazel/testing_server.py index 66906ad0d5..583e3ce86d 100644 --- a/src/test/shell/bazel/testing_server.py +++ b/src/test/shell/bazel/testing_server.py @@ -62,8 +62,8 @@ class Handler(BaseHTTPRequestHandler): self.wfile.write('not authenticated') def serve_file(self): - file_to_serve = open(str(os.getcwd()) + self.path) - self.wfile.write(file_to_serve.read()) + with open(str(os.getcwd()) + self.path) as file_to_serve: + self.wfile.write(file_to_serve.read()) if __name__ == '__main__': -- cgit v1.2.3