Skip to content

Commit ca74f93

Browse files
author
Jakub Kaczmarzyk
committed
add: tests for nibabel.save
1 parent 0711965 commit ca74f93

File tree

1 file changed

+32
-1
lines changed

1 file changed

+32
-1
lines changed

nibabel/tests/test_loadsave.py

Lines changed: 32 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,8 @@
1010
from .. import (Spm99AnalyzeImage, Spm2AnalyzeImage,
1111
Nifti1Pair, Nifti1Image,
1212
Nifti2Pair, Nifti2Image)
13-
from ..loadsave import load, read_img_data
13+
from ..spatialimages import SpatialImage
14+
from ..loadsave import load, read_img_data, save
1415
from ..filebasedimages import ImageFileError
1516
from ..tmpdirs import InTemporaryDirectory, TemporaryDirectory
1617

@@ -135,3 +136,33 @@ def test_read_img_data_nifti():
135136
assert_array_equal(exp_offset, read_img_data(img_back))
136137
# Delete stuff that might hold onto file references
137138
del img, img_back, data_back
139+
140+
141+
def test_save():
142+
with InTemporaryDirectory():
143+
dataobj = np.ones((10, 10, 10), dtype=np.float16)
144+
affine = np.eye(4, dtype=np.float32)
145+
img = SpatialImage(dataobj, affine)
146+
147+
# The `save` method can raise one of many types of errors, but they are
148+
# all subclasses of Exception. This attempt will fail because float16
149+
# is not supported.
150+
with assert_raises(Exception):
151+
save(img, 'foo.nii.gz')
152+
153+
# Test the saving of several types of images.
154+
dataobj = np.ones((10, 10, 10), dtype=np.float32)
155+
img = SpatialImage(dataobj, affine)
156+
for ext in {'hdr', 'img', 'nii', 'nii.gz', 'mgz'}:
157+
this_filepath = "foo." + ext
158+
save(img, this_filepath)
159+
img_loaded = load(this_filepath)
160+
assert_array_equal(np.asarray(img_loaded.dataobj), dataobj)
161+
assert_array_equal(np.asarray(img_loaded.affine), affine)
162+
163+
# Test not being able to work out file type.
164+
with assert_raises(ImageFileError):
165+
save(img, 'foo.noexists')
166+
167+
# Delete stuff that might hold onto file references
168+
del img, img_loaded

0 commit comments

Comments
 (0)