99'''Tests for mghformat reading writing'''
1010
1111import os
12+ import io
13+ import gzip
1214
1315import numpy as np
1416
1517from ...externals .six import BytesIO
16- from .. import load , save , MGHImage
17- from ..mghformat import MGHHeader , MGHError
18+ from .. import load , save
19+ from ...openers import ImageOpener
20+ from ..mghformat import MGHHeader , MGHError , MGHImage
1821from ...tmpdirs import InTemporaryDirectory
1922from ...fileholders import FileHolder
2023
2831
2932from ...tests import test_spatialimages as tsi
3033
34+ MGZ_FNAME = os .path .join (data_path , 'test.mgz' )
35+
3136# sample voxel to ras matrix (mri_info --vox2ras)
3237v2r = np .array ([[1 , 2 , 3 , - 13 ], [2 , 3 , 1 , - 11.5 ],
3338 [3 , 1 , 2 , - 11.5 ], [0 , 0 , 0 , 1 ]], dtype = np .float32 )
@@ -43,8 +48,7 @@ def test_read_mgh():
4348 # mri_volsynth --dim 3 4 5 2 --vol test.mgz
4449 # --cdircos 1 2 3 --rdircos 2 3 1 --sdircos 3 1 2
4550 # mri_volsynth is a FreeSurfer command
46- mgz_path = os .path .join (data_path , 'test.mgz' )
47- mgz = load (mgz_path )
51+ mgz = load (MGZ_FNAME )
4852
4953 # header
5054 h = mgz .header
@@ -165,8 +169,7 @@ def test_header_updating():
165169 # Don't update the header information if the affine doesn't change.
166170 # Luckily the test.mgz dataset had a bad set of cosine vectors, so these
167171 # will be changed if the affine gets updated
168- mgz_path = os .path .join (data_path , 'test.mgz' )
169- mgz = load (mgz_path )
172+ mgz = load (MGZ_FNAME )
170173 hdr = mgz .header
171174 # Test against mri_info output
172175 exp_aff = np .loadtxt (BytesIO (b"""
@@ -230,6 +233,26 @@ def test_header_slope_inter():
230233 assert_equal (hdr .get_slope_inter (), (None , None ))
231234
232235
236+ def test_mgh_load_fileobj ():
237+ # Checks the filename gets passed to array proxy
238+ #
239+ # This is a bit of an implementation detail, but the test is to make sure
240+ # that we aren't passing ImageOpener objects to the array proxy, as these
241+ # were confusing mmap on Python 3. If there's some sensible reason not to
242+ # pass the filename to the array proxy, please feel free to change this
243+ # test.
244+ img = MGHImage .load (MGZ_FNAME )
245+ assert_equal (img .dataobj .file_like , MGZ_FNAME )
246+ # Check fileobj also passed into dataobj
247+ with ImageOpener (MGZ_FNAME ) as fobj :
248+ contents = fobj .read ()
249+ bio = io .BytesIO (contents )
250+ fm = MGHImage .make_file_map (mapping = dict (image = bio ))
251+ img2 = MGHImage .from_file_map (fm )
252+ assert_true (img2 .dataobj .file_like is bio )
253+ assert_array_equal (img .get_data (), img2 .get_data ())
254+
255+
233256class TestMGHImage (tsi .TestSpatialImage , tsi .MmapImageMixin ):
234257 """ Apply general image tests to MGHImage
235258 """
0 commit comments