Explicitly close a bunch of resources

This commit is contained in:
Kovid Goyal 2023-10-16 12:03:44 +05:30
parent 1e9a543e54
commit 6e3b948bc9
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
3 changed files with 20 additions and 8 deletions

View File

@ -311,7 +311,8 @@ def find_tests():
def convert_mock(path, temp_path, key, instance):
self.ae(instance['status'], 'working')
self.ae(instance['key'], key)
open(os.path.join(temp_path, instance['path'], 'sentinel'), 'wb').write(b'test')
with open(os.path.join(temp_path, instance['path'], 'sentinel'), 'wb') as f:
f.write(b'test')
def set_data(x):
if not isinstance(x, bytes):

View File

@ -419,10 +419,10 @@ class BuildTest(unittest.TestCase):
--- ZLIB (PNG/ZIP) support ok
'''.splitlines():
self.assertIn(line.strip(), out)
i = Image.open(I('lt.png', allow_user_override=False))
self.assertGreaterEqual(i.size, (20, 20))
i = Image.open(P('catalog/DefaultCover.jpg', allow_user_override=False))
self.assertGreaterEqual(i.size, (20, 20))
with Image.open(I('lt.png', allow_user_override=False)) as i:
self.assertGreaterEqual(i.size, (20, 20))
with Image.open(P('catalog/DefaultCover.jpg', allow_user_override=False)) as i:
self.assertGreaterEqual(i.size, (20, 20))
@unittest.skipUnless(iswindows and not is_ci, 'File dialog helper only used on windows (non-continuous-integration)')
def test_file_dialog_helper(self):

View File

@ -578,10 +578,17 @@ def run_optimizer(file_path, cmd, as_filter=False, input_data=None):
outw.start()
raw = force_unicode(stderr.read())
if p.wait() != 0:
p.stdout.close()
if as_filter:
p.stderr.close()
p.stdin.close()
return raw
else:
if as_filter:
outw.join(60.0), inw.join(60.0)
p.stdin.close()
p.stderr.close()
p.stdout.close()
try:
sz = os.path.getsize(outfile)
except OSError:
@ -645,7 +652,9 @@ def encode_jpeg(file_path, quality=80):
buf.open(QIODevice.OpenModeFlag.WriteOnly)
if not img.save(buf, 'PPM'):
raise ValueError('Failed to export image to PPM')
return run_optimizer(file_path, cmd, as_filter=True, input_data=ReadOnlyFileBuffer(ba.data()))
data = ReadOnlyFileBuffer(ba.data())
buf.close()
return run_optimizer(file_path, cmd, as_filter=True, input_data=data)
def encode_webp(file_path, quality=75, m=6, metadata='all'):
@ -684,9 +693,11 @@ def test(): # {{{
despeckle_image(img)
remove_borders_from_image(img)
image_to_data(img, fmt='GIF')
raw = subprocess.Popen([get_exe_path('JxrDecApp'), '-h'],
p = subprocess.Popen([get_exe_path('JxrDecApp'), '-h'],
creationflags=subprocess.DETACHED_PROCESS if iswindows else 0,
stdout=subprocess.PIPE).stdout.read()
stdout=subprocess.PIPE)
raw, _ = p.communicate()
p.wait()
if b'JPEG XR Decoder Utility' not in raw:
raise SystemExit('Failed to run JxrDecApp')
# }}}