From 5fc243a93dba437f32857e7c5f13a7609a69bdbe Mon Sep 17 00:00:00 2001 From: Kovid Goyal Date: Mon, 16 Oct 2023 19:05:02 +0530 Subject: [PATCH] More explicit resource closing --- src/calibre/gui2/viewer/convert_book.py | 9 ++++--- src/calibre/utils/shared_file.py | 35 +++++++++++++++---------- 2 files changed, 27 insertions(+), 17 deletions(-) diff --git a/src/calibre/gui2/viewer/convert_book.py b/src/calibre/gui2/viewer/convert_book.py index 73ef247b2a..03f0b3feac 100644 --- a/src/calibre/gui2/viewer/convert_book.py +++ b/src/calibre/gui2/viewer/convert_book.py @@ -323,7 +323,10 @@ def find_tests(): book_src = os.path.join(self.tdir, 'book.epub') set_data('a') path = prepare_book(book_src, convert_func=convert_mock) - self.ae(open(os.path.join(path, 'sentinel'), 'rb').read(), b'test') + def read(x, mode='r'): + with open(x, mode) as f: + return f.read() + self.ae(read(os.path.join(path, 'sentinel'), 'rb'), b'test') # Test that opening the same book uses the cache second_path = prepare_book(book_src, convert_func=convert_mock) @@ -366,11 +369,11 @@ def find_tests(): book_src = os.path.join(self.tdir, 'book2.epub') set_data('bb') path = prepare_book(book_src, convert_func=convert_mock) - self.ae(open(os.path.join(path, 'sentinel'), 'rb').read(), b'test') + self.ae(read(os.path.join(path, 'sentinel'), 'rb'), b'test') bs = os.stat(book_src) set_data('cde') update_book(book_src, bs, name_data_map={'sentinel': b'updated'}) - self.ae(open(os.path.join(path, 'sentinel'), 'rb').read(), b'updated') + self.ae(read(os.path.join(path, 'sentinel'), 'rb'), b'updated') self.ae(1, len(os.listdir(os.path.join(book_cache_dir(), 'f')))) with cache_lock() as f: metadata = json.loads(f.read()) diff --git a/src/calibre/utils/shared_file.py b/src/calibre/utils/shared_file.py index e5a644430e..a2fef575cc 100644 --- a/src/calibre/utils/shared_file.py +++ b/src/calibre/utils/shared_file.py @@ -116,20 +116,27 @@ def find_tests(): f.write(b'a' * 20 * 1024) eq(fname, f.name) f = share_open(fname, 'rb') - eq(f.read(1), b'a') - if iswindows: - os.rename(fname, fname+'.moved') - os.remove(fname+'.moved') - else: - os.remove(fname) - eq(f.read(1), b'a') - f2 = share_open(fname, 'w+b') - f2.write(b'b' * 10 * 1024) - f2.seek(0) - eq(f.read(10000), b'a'*10000) - eq(f2.read(100), b'b' * 100) - f3 = share_open(fname, 'rb') - eq(f3.read(100), b'b' * 100) + close = [f] + try: + eq(f.read(1), b'a') + if iswindows: + os.rename(fname, fname+'.moved') + os.remove(fname+'.moved') + else: + os.remove(fname) + eq(f.read(1), b'a') + f2 = share_open(fname, 'w+b') + close.append(f2) + f2.write(b'b' * 10 * 1024) + f2.seek(0) + eq(f.read(10000), b'a'*10000) + eq(f2.read(100), b'b' * 100) + f3 = share_open(fname, 'rb') + close.append(f3) + eq(f3.read(100), b'b' * 100) + finally: + for f in close: + f.close() return unittest.defaultTestLoader.loadTestsFromTestCase(SharedFileTest)