2323from numpy .testing import assert_array_equal , assert_array_almost_equal
2424from nose .tools import (assert_true , assert_false , assert_equal ,
2525 assert_not_equal , assert_raises )
26+ from nibabel .testing import VIRAL_MEMMAP
2627
2728from .test_fileslice import slicer_samples
2829
@@ -182,10 +183,37 @@ def test_mmap():
182183 check_mmap (hdr , hdr .get_data_offset (), ArrayProxy )
183184
184185
185- def check_mmap (hdr , offset , proxy_class , check_mode = True ):
186+ def check_mmap (hdr , offset , proxy_class ,
187+ has_scaling = False ,
188+ unscaled_is_view = True ):
189+ """ Assert that array proxies return memory maps as expected
190+
191+ Parameters
192+ ----------
193+ hdr : object
194+ Image header instance
195+ offset : int
196+ Offset in bytes of image data in file (that we will write)
197+ proxy_class : class
198+ Class of image array proxy to test
199+ has_scaling : {False, True}
200+ True if the `hdr` says to apply scaling to the output data, False
201+ otherwise.
202+ unscaled_is_view : {True, False}
203+ True if getting the unscaled data returns a view of the array. If
204+ False, then type of returned array will depend on whether numpy has the
205+ old viral (< 1.12) memmap behavior (returns memmap) or the new behavior
206+ (returns ndarray). See: https://github.com/numpy/numpy/pull/7406
207+ """
186208 shape = hdr .get_data_shape ()
187209 arr = np .arange (np .prod (shape ), dtype = hdr .get_data_dtype ()).reshape (shape )
188210 fname = 'test.bin'
211+ # Whether unscaled array memory backed by memory map (regardless of what
212+ # numpy says).
213+ unscaled_really_mmap = unscaled_is_view
214+ # Whether scaled array memory backed by memory map (regardless of what
215+ # numpy says).
216+ scaled_really_mmap = unscaled_really_mmap and not has_scaling
189217 with InTemporaryDirectory ():
190218 with open (fname , 'wb' ) as fobj :
191219 fobj .write (b' ' * offset )
@@ -205,13 +233,17 @@ def check_mmap(hdr, offset, proxy_class, check_mode=True):
205233 prox = proxy_class (fname , hdr , ** kwargs )
206234 unscaled = prox .get_unscaled ()
207235 back_data = np .asanyarray (prox )
236+ unscaled_is_mmap = isinstance (unscaled , np .memmap )
237+ back_is_mmap = isinstance (back_data , np .memmap )
208238 if expected_mode is None :
209- assert_false (isinstance ( unscaled , np . memmap ) )
210- assert_false (isinstance ( back_data , np . memmap ) )
239+ assert_false (unscaled_is_mmap )
240+ assert_false (back_is_mmap )
211241 else :
212- assert_true (isinstance (unscaled , np .memmap ))
213- assert_true (isinstance (back_data , np .memmap ))
214- if check_mode :
242+ assert_equal (unscaled_is_mmap ,
243+ VIRAL_MEMMAP or unscaled_really_mmap )
244+ assert_equal (back_is_mmap ,
245+ VIRAL_MEMMAP or scaled_really_mmap )
246+ if scaled_really_mmap :
215247 assert_equal (back_data .mode , expected_mode )
216248 del prox , back_data
217249 # Check that mmap is keyword-only
0 commit comments