Skip to content

Commit 0c902d2

Browse files
committed
TEST: Unit test to make sure that keep_file_open works for pre-opened file objects
1 parent 17fea73 commit 0c902d2

File tree

1 file changed

+26
-5
lines changed

1 file changed

+26
-5
lines changed

nibabel/tests/test_arrayproxy.py

Lines changed: 26 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -335,7 +335,6 @@ def check_mmap(hdr, offset, proxy_class,
335335
def test_keep_file_open():
336336
# Test the behaviour of the keep_file_open __init__ flag.
337337
numopeners = [0]
338-
339338
class CountingImageOpener(ImageOpener):
340339

341340
def __init__(self, *args, **kwargs):
@@ -345,24 +344,46 @@ def __init__(self, *args, **kwargs):
345344

346345
fname = 'testdata'
347346
dtype = np.float32
348-
data = np.arange(1000, dtype=np.float32).reshape((10, 10, 10))
347+
data = np.arange(1000, dtype=dtype).reshape((10, 10, 10))
348+
voxels = np.random.randint(0, 10, (10, 3))
349349
with InTemporaryDirectory():
350350
with open(fname, 'wb') as fobj:
351351
fobj.write(data.tostring(order='F'))
352+
# Test that ArrayProxy(keep_file_open=True) only creates one file
353+
# handle, and that ArrayProxy(keep_file_open=False) creates a file
354+
# handle on every data access.
352355
with mock.patch('nibabel.arrayproxy.ImageOpener', CountingImageOpener):
353356
proxy_no_kfp = ArrayProxy(fname, ((10, 10, 10), dtype))
354-
proxy_kfp = ArrayProxy(fname, ((10, 10, 10), dtype),
355-
keep_file_open=True)
356-
voxels = np.random.randint(0, 10, (10, 3))
357357
for i in range(voxels.shape[0]):
358358
x , y, z = [int(c) for c in voxels[i, :]]
359359
assert proxy_no_kfp[x, y, z] == x * 100 + y * 10 + z
360360
assert numopeners[0] == i + 1
361361
numopeners[0] = 0
362+
proxy_kfp = ArrayProxy(fname, ((10, 10, 10), dtype),
363+
keep_file_open=True)
362364
for i in range(voxels.shape[0]):
363365
x , y, z = [int(c) for c in voxels[i, :]]
364366
assert proxy_kfp[x, y, z] == x * 100 + y * 10 + z
365367
assert numopeners[0] == 1
368+
# Test that the keep_file_open flag has no effect if an open file
369+
# handle is passed in
370+
with open(fname, 'rb') as fobj:
371+
proxy_no_kfp = ArrayProxy(fobj, ((10, 10, 10), dtype),
372+
keep_file_open=False)
373+
for i in range(voxels.shape[0]):
374+
assert proxy_no_kfp[x, y, z] == x * 100 + y * 10 + z
375+
assert not fobj.closed
376+
del proxy_no_kfp
377+
proxy_no_kfp = None
378+
assert not fobj.closed
379+
proxy_kfp = ArrayProxy(fobj, ((10, 10, 10), dtype),
380+
keep_file_open=True)
381+
for i in range(voxels.shape[0]):
382+
assert proxy_kfp[x, y, z] == x * 100 + y * 10 + z
383+
assert not fobj.closed
384+
del proxy_kfp
385+
proxy_kfp = None
386+
assert not fobj.closed
366387

367388

368389
def test_pickle_lock():

0 commit comments

Comments
 (0)