Skip to content

Commit f920efa

Browse files
committed
enh: finalize some tests to increase coverage
1 parent 1a52ca0 commit f920efa

File tree

6 files changed

+57
-27
lines changed

6 files changed

+57
-27
lines changed

nitransforms/base.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -225,13 +225,13 @@ def apply(self, spatialimage, reference=None,
225225
226226
"""
227227
if reference is not None and isinstance(reference, (str, Path)):
228-
reference = load(reference)
228+
reference = load(str(reference))
229229

230230
_ref = self.reference if reference is None \
231231
else SpatialReference.factory(reference)
232232

233233
if isinstance(spatialimage, (str, Path)):
234-
spatialimage = load(spatialimage)
234+
spatialimage = load(str(spatialimage))
235235

236236
data = np.asanyarray(spatialimage.dataobj)
237237
output_dtype = output_dtype or data.dtype

nitransforms/io/afni.py

Lines changed: 15 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@
44
from nibabel.affines import obliquity, voxel_sizes
55

66
from ..patched import shape_zoom_affine
7-
from .base import BaseLinearTransformList, LinearParameters
7+
from .base import BaseLinearTransformList, LinearParameters, TransformFileError
88

99
LPS = np.diag([-1, -1, 1, 1])
1010
OBLIQUITY_THRESHOLD_DEG = 0.01
@@ -58,14 +58,14 @@ def from_string(cls, string):
5858
"""Read the struct from string."""
5959
tf = cls()
6060
sa = tf.structarr
61-
lines = [l for l in string.splitlines()
62-
if l.strip() and not l.startswith('#')]
63-
64-
if '3dvolreg matrices' in lines[0]:
65-
lines = lines[1:] # Drop header
61+
lines = [
62+
l for l in string.splitlines()
63+
if l.strip() and not (l.startswith('#') or '3dvolreg matrices' in l)
64+
]
6665

6766
if not lines:
68-
raise ValueError('String "%s"' % string)
67+
raise TransformFileError
68+
6969
parameters = np.vstack((
7070
np.genfromtxt([lines[0].encode()],
7171
dtype='f8').reshape((3, 4)),
@@ -108,9 +108,14 @@ def from_ras(cls, ras, moving=None, reference=None):
108108
def from_string(cls, string):
109109
"""Read the struct from string."""
110110
_self = cls()
111-
_self.xforms = [cls._inner_type.from_string(l.strip())
112-
for l in string.splitlines()
113-
if l.strip() and not l.startswith('#')]
111+
112+
lines = [l.strip() for l in string.splitlines()
113+
if l.strip() and not l.startswith('#')]
114+
if not lines:
115+
raise TransformFileError('Input string is empty.')
116+
117+
_self.xforms = [cls._inner_type.from_string(l)
118+
for l in lines]
114119
return _self
115120

116121

nitransforms/io/fsl.py

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
import numpy as np
44
from nibabel.affines import voxel_sizes
55

6-
from .base import BaseLinearTransformList, LinearParameters
6+
from .base import BaseLinearTransformList, LinearParameters, TransformFileError
77

88

99
class FSLLinearTransform(LinearParameters):
@@ -45,8 +45,14 @@ def from_string(cls, string):
4545
"""Read the struct from string."""
4646
tf = cls()
4747
sa = tf.structarr
48+
lines = [l.strip() for l in string.splitlines()
49+
if l.strip()]
50+
if not lines or len(lines) < 4:
51+
raise TransformFileError
52+
53+
print(lines)
4854
sa['parameters'] = np.genfromtxt(
49-
[string], dtype=cls.dtype['parameters'])
55+
['\n'.join(lines)], dtype=cls.dtype['parameters'])
5056
return tf
5157

5258

@@ -92,8 +98,7 @@ def from_ras(cls, ras, moving=None, reference=None):
9298
def from_string(cls, string):
9399
"""Read the struct from string."""
94100
_self = cls()
95-
_self.xforms = [cls._inner_type.from_string(l.strip())
96-
for l in string.splitlines() if l.strip()]
101+
_self.xforms = [cls._inner_type.from_string(string)]
97102
return _self
98103

99104
@classmethod

nitransforms/io/itk.py

Lines changed: 8 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -131,9 +131,11 @@ def from_string(cls, string):
131131
"""Read the struct from string."""
132132
tf = cls()
133133
sa = tf.structarr
134-
lines = [l for l in string.splitlines()
134+
lines = [l.strip() for l in string.splitlines()
135135
if l.strip()]
136-
assert lines[0][0] == '#'
136+
if not lines or not lines[0].startswith('#'):
137+
raise TransformFileError
138+
137139
if lines[1][0] == '#':
138140
lines = lines[1:] # Drop banner with version
139141

@@ -182,7 +184,7 @@ def to_string(self):
182184
strings = []
183185
for i, xfm in enumerate(self.xforms):
184186
xfm.structarr['index'] = i
185-
strings.append(xfm.to_string())
187+
strings.append(xfm.to_string(banner=(i == 0)))
186188
return '\n'.join(strings)
187189

188190
@classmethod
@@ -223,8 +225,9 @@ def from_string(cls, string):
223225
lines = [l.strip() for l in string.splitlines()
224226
if l.strip()]
225227

226-
if lines[0][0] != '#' or 'Insight Transform File V1.0' not in lines[0]:
227-
raise ValueError('Unknown Insight Transform File format.')
228+
if not lines or not lines[0].startswith('#') or \
229+
'Insight Transform File V1.0' not in lines[0]:
230+
raise TransformFileError('Unknown Insight Transform File format.')
228231

229232
string = '\n'.join(lines[1:])
230233
for xfm in string.split('#')[1:]:

nitransforms/tests/test_base.py

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -76,21 +76,21 @@ def _to_hdf5(klass, x5_root):
7676

7777
monkeypatch.setattr(TransformBase, 'map', _fakemap)
7878
monkeypatch.setattr(TransformBase, '_to_hdf5', _to_hdf5)
79-
fname = str(data_path / 'someones_anatomy.nii.gz')
79+
fname = data_path / 'someones_anatomy.nii.gz'
8080

8181
# Test identity transform
8282
xfm = TransformBase()
8383
xfm.reference = fname
8484
assert xfm.ndim == 3
8585
moved = xfm.apply(fname, order=0)
86-
assert np.all(nb.load(fname).get_fdata() == moved.get_fdata())
86+
assert np.all(nb.load(str(fname)).get_fdata() == moved.get_fdata())
8787

8888
# Test identity transform - setting reference
8989
xfm = TransformBase()
9090
xfm.reference = fname
9191
assert xfm.ndim == 3
92-
moved = xfm.apply(fname, reference=fname, order=0)
93-
assert np.all(nb.load(fname).get_fdata() == moved.get_fdata())
92+
moved = xfm.apply(str(fname), reference=fname, order=0)
93+
assert np.all(nb.load(str(fname)).get_fdata() == moved.get_fdata())
9494

9595
# Test applying to Gifti
9696
gii = nb.gifti.GiftiImage(darrays=[

nitransforms/tests/test_io.py

Lines changed: 19 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -120,14 +120,22 @@ def test_Linear_common(tmpdir, data_path, sw, image_orientation,
120120
ext = '.lta'
121121
factory = fs.LinearTransformArray
122122

123+
with pytest.raises(TransformFileError):
124+
factory.from_string('')
125+
123126
fname = 'affine-%s.%s%s' % (image_orientation, sw, ext)
124127

125128
# Test the transform loaders are implemented
126129
xfm = factory.from_filename(data_path / fname)
127130

128131
with open(str(data_path / fname)) as f:
132+
text = f.read()
133+
f.seek(0)
129134
xfm = factory.from_fileobj(f)
130135

136+
# Test to_string
137+
assert text == xfm.to_string()
138+
131139
xfm.to_filename(fname)
132140
assert filecmp.cmp(fname, str((data_path / fname).resolve()))
133141

@@ -142,7 +150,7 @@ def test_Linear_common(tmpdir, data_path, sw, image_orientation,
142150
])
143151
@pytest.mark.parametrize('sw', ['afni', 'fsl', 'itk'])
144152
def test_LinearList_common(tmpdir, data_path, sw, image_orientation,
145-
get_testdata):
153+
get_testdata):
146154
tmpdir.chdir()
147155

148156
angles = np.random.uniform(low=-3.14, high=3.14, size=(5, 3))
@@ -162,13 +170,22 @@ def test_LinearList_common(tmpdir, data_path, sw, image_orientation,
162170
tflist1 = factory(mats)
163171

164172
fname = 'affine-%s.%s%s' % (image_orientation, sw, ext)
173+
174+
with pytest.raises(FileNotFoundError):
175+
factory.from_filename(fname)
176+
177+
tmpdir.join('singlemat.%s' % ext).write('')
178+
with pytest.raises(TransformFileError):
179+
factory.from_filename('singlemat.%s' % ext)
180+
165181
tflist1.to_filename(fname)
166182
tflist2 = factory.from_filename(fname)
167183

168184
assert tflist1['nxforms'] == tflist2['nxforms']
169185
assert all([np.allclose(x1['parameters'], x2['parameters'])
170186
for x1, x2 in zip(tflist1.xforms, tflist2.xforms)])
171187

188+
172189
def test_ITKLinearTransform(tmpdir, data_path):
173190
tmpdir.chdir()
174191

@@ -223,7 +240,7 @@ def test_ITKLinearTransformArray(tmpdir, data_path):
223240

224241
assert itklist['nxforms'] == 9
225242
assert text == itklist.to_string()
226-
with pytest.raises(ValueError):
243+
with pytest.raises(TransformFileError):
227244
itk.ITKLinearTransformArray.from_string(
228245
'\n'.join(text.splitlines()[1:]))
229246

0 commit comments

Comments
 (0)