@@ -335,7 +335,6 @@ def check_mmap(hdr, offset, proxy_class,
335
335
def test_keep_file_open ():
336
336
# Test the behaviour of the keep_file_open __init__ flag.
337
337
numopeners = [0 ]
338
-
339
338
class CountingImageOpener (ImageOpener ):
340
339
341
340
def __init__ (self , * args , ** kwargs ):
@@ -345,24 +344,46 @@ def __init__(self, *args, **kwargs):
345
344
346
345
fname = 'testdata'
347
346
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 ))
349
349
with InTemporaryDirectory ():
350
350
with open (fname , 'wb' ) as fobj :
351
351
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.
352
355
with mock .patch ('nibabel.arrayproxy.ImageOpener' , CountingImageOpener ):
353
356
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 ))
357
357
for i in range (voxels .shape [0 ]):
358
358
x , y , z = [int (c ) for c in voxels [i , :]]
359
359
assert proxy_no_kfp [x , y , z ] == x * 100 + y * 10 + z
360
360
assert numopeners [0 ] == i + 1
361
361
numopeners [0 ] = 0
362
+ proxy_kfp = ArrayProxy (fname , ((10 , 10 , 10 ), dtype ),
363
+ keep_file_open = True )
362
364
for i in range (voxels .shape [0 ]):
363
365
x , y , z = [int (c ) for c in voxels [i , :]]
364
366
assert proxy_kfp [x , y , z ] == x * 100 + y * 10 + z
365
367
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
366
387
367
388
368
389
def test_pickle_lock ():
0 commit comments