More explicit resource closing

This commit is contained in:
Kovid Goyal 2023-10-16 19:05:02 +05:30
parent 6660bd828b
commit 5fc243a93d
No known key found for this signature in database
GPG Key ID: 06BC317B515ACE7C
2 changed files with 27 additions and 17 deletions

View File

@ -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())

View File

@ -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)