Merge pull request #787 from scop/with

Handle more stream closing with "with"
This commit is contained in:
Mathieu Pillard 2016-08-04 11:17:28 +02:00 committed by GitHub
commit 7f5a743951
3 changed files with 18 additions and 21 deletions

View File

@ -70,21 +70,17 @@ class GzipCompressorFileStorage(CompressorFileStorage):
orig_path = self.path(filename)
compressed_path = '%s.gz' % orig_path
f_in = open(orig_path, 'rb')
f_out = open(compressed_path, 'wb')
try:
f_out = gzip.GzipFile(fileobj=f_out)
f_out.write(f_in.read())
finally:
f_out.close()
f_in.close()
# Ensure the file timestamps match.
# os.stat() returns nanosecond resolution on Linux, but os.utime()
# only sets microsecond resolution. Set times on both files to
# ensure they are equal.
stamp = time.time()
os.utime(orig_path, (stamp, stamp))
os.utime(compressed_path, (stamp, stamp))
with open(orig_path, 'rb') as f_in, open(compressed_path, 'wb') as f_out:
with gzip.GzipFile(fileobj=f_out) as gz_out:
gz_out.write(f_in.read())
# Ensure the file timestamps match.
# os.stat() returns nanosecond resolution on Linux, but os.utime()
# only sets microsecond resolution. Set times on both files to
# ensure they are equal.
stamp = time.time()
os.utime(orig_path, (stamp, stamp))
os.utime(compressed_path, (stamp, stamp))
return filename

View File

@ -16,9 +16,8 @@ def main():
options, arguments = p.parse_args()
if options.filename:
f = open(options.filename)
content = f.read()
f.close()
with open(options.filename) as f:
content = f.read()
else:
content = sys.stdin.read()

View File

@ -405,7 +405,8 @@ class CompressorInDebugModeTestCase(SimpleTestCase):
# files can be outdated
css_filename = os.path.join(settings.COMPRESS_ROOT, "css", "one.css")
# Store the hash of the original file's content
css_content = open(css_filename).read()
with open(css_filename) as f:
css_content = f.read()
hashed = get_hexdigest(css_content, 12)
# Now modify the file in the STATIC_ROOT
test_css_content = "p { font-family: 'test' }"
@ -419,6 +420,7 @@ class CompressorInDebugModeTestCase(SimpleTestCase):
compressor.storage = DefaultStorage()
output = compressor.output()
self.assertEqual(expected, output)
result = open(os.path.join(settings.COMPRESS_ROOT, "CACHE", "css",
"%s.css" % hashed), "r").read()
with open(os.path.join(settings.COMPRESS_ROOT, "CACHE", "css",
"%s.css" % hashed), "r") as f:
result = f.read()
self.assertTrue(test_css_content not in result)