diff --git a/nibabel/streamlines/tests/test_array_sequence.py b/nibabel/streamlines/tests/test_array_sequence.py index c92580accb..68da78783f 100644 --- a/nibabel/streamlines/tests/test_array_sequence.py +++ b/nibabel/streamlines/tests/test_array_sequence.py @@ -5,8 +5,8 @@ import itertools import numpy as np -from nose.tools import assert_equal, assert_raises, assert_true -from nibabel.testing import assert_arrays_equal +import pytest +from ...testing_pytest import assert_arrays_equal from numpy.testing import assert_array_equal from ..array_sequence import ArraySequence, is_array_sequence, concatenate @@ -15,7 +15,7 @@ SEQ_DATA = {} -def setup(): +def setup_module(): global SEQ_DATA rng = np.random.RandomState(42) SEQ_DATA['rng'] = rng @@ -30,22 +30,25 @@ def generate_data(nb_arrays, common_shape, rng): def check_empty_arr_seq(seq): - assert_equal(len(seq), 0) - assert_equal(len(seq._offsets), 0) - assert_equal(len(seq._lengths), 0) + assert len(seq) == 0 + assert len(seq._offsets) == 0 + assert len(seq._lengths) == 0 # assert_equal(seq._data.ndim, 0) - assert_equal(seq._data.ndim, 1) - assert_true(seq.common_shape == ()) + assert seq._data.ndim == 1 + + # TODO: Check assert_true + # assert_true(seq.common_shape == ()) def check_arr_seq(seq, arrays): lengths = list(map(len, arrays)) - assert_true(is_array_sequence(seq)) - assert_equal(len(seq), len(arrays)) - assert_equal(len(seq._offsets), len(arrays)) - assert_equal(len(seq._lengths), len(arrays)) - assert_equal(seq._data.shape[1:], arrays[0].shape[1:]) - assert_equal(seq.common_shape, arrays[0].shape[1:]) + assert is_array_sequence(seq) + assert len(seq) == len(arrays) + assert len(seq._offsets) == len(arrays) + assert len(seq._lengths) == len(arrays) + assert seq._data.shape[1:] == arrays[0].shape[1:] + assert seq.common_shape == arrays[0].shape[1:] + assert_arrays_equal(seq, arrays) # If seq is a view, then order of internal data is not guaranteed. @@ -54,18 +57,20 @@ def check_arr_seq(seq, arrays): assert_array_equal(sorted(seq._lengths), sorted(lengths)) else: seq.shrink_data() - assert_equal(seq._data.shape[0], sum(lengths)) + + assert seq._data.shape[0] == sum(lengths) + assert_array_equal(seq._data, np.concatenate(arrays, axis=0)) assert_array_equal(seq._offsets, np.r_[0, np.cumsum(lengths)[:-1]]) assert_array_equal(seq._lengths, lengths) def check_arr_seq_view(seq_view, seq): - assert_true(seq_view._is_view) - assert_true(seq_view is not seq) - assert_true(np.may_share_memory(seq_view._data, seq._data)) - assert_true(seq_view._offsets is not seq._offsets) - assert_true(seq_view._lengths is not seq._lengths) + assert seq_view._is_view is True + assert seq_view is not seq + assert (np.may_share_memory(seq_view._data, seq._data)) is True + assert seq_view._offsets is not seq._offsets + assert seq_view._lengths is not seq._lengths class TestArraySequence(unittest.TestCase): @@ -97,8 +102,8 @@ def test_creating_arraysequence_from_generator(self): seq_with_buffer = ArraySequence(gen_2, buffer_size=256) # Check buffer size effect - assert_equal(seq_with_buffer.data.shape, seq.data.shape) - assert_true(seq_with_buffer._buffer_size > seq._buffer_size) + assert seq_with_buffer.data.shape == seq.data.shape + assert seq_with_buffer._buffer_size > seq._buffer_size # Check generator result check_arr_seq(seq, SEQ_DATA['data']) @@ -121,26 +126,27 @@ def test_arraysequence_iter(self): # Try iterating through a corrupted ArraySequence object. seq = SEQ_DATA['seq'].copy() seq._lengths = seq._lengths[::2] - assert_raises(ValueError, list, seq) + with pytest.raises(ValueError): + list(seq) def test_arraysequence_copy(self): orig = SEQ_DATA['seq'] seq = orig.copy() n_rows = seq.total_nb_rows - assert_equal(n_rows, orig.total_nb_rows) + assert n_rows == orig.total_nb_rows assert_array_equal(seq._data, orig._data[:n_rows]) - assert_true(seq._data is not orig._data) + assert seq._data is not orig._data assert_array_equal(seq._offsets, orig._offsets) - assert_true(seq._offsets is not orig._offsets) + assert seq._offsets is not orig._offsets assert_array_equal(seq._lengths, orig._lengths) - assert_true(seq._lengths is not orig._lengths) - assert_equal(seq.common_shape, orig.common_shape) + assert seq._lengths is not orig._lengths + assert seq.common_shape == orig.common_shape # Taking a copy of an `ArraySequence` generated by slicing. # Only keep needed data. seq = orig[::2].copy() check_arr_seq(seq, SEQ_DATA['data'][::2]) - assert_true(seq._data is not orig._data) + assert seq._data is not orig._data def test_arraysequence_append(self): element = generate_data(nb_arrays=1, @@ -171,7 +177,9 @@ def test_arraysequence_append(self): element = generate_data(nb_arrays=1, common_shape=SEQ_DATA['seq'].common_shape*2, rng=SEQ_DATA['rng'])[0] - assert_raises(ValueError, seq.append, element) + + with pytest.raises(ValueError): + seq.append(element) def test_arraysequence_extend(self): new_data = generate_data(nb_arrays=10, @@ -217,7 +225,8 @@ def test_arraysequence_extend(self): common_shape=SEQ_DATA['seq'].common_shape*2, rng=SEQ_DATA['rng']) seq = SEQ_DATA['seq'].copy() # Copy because of in-place modification. - assert_raises(ValueError, seq.extend, data) + with pytest.raises(ValueError): + seq.extend(data) # Extend after extracting some slice working_slice = seq[:2] @@ -262,7 +271,9 @@ def test_arraysequence_getitem(self): for i, keep in enumerate(selection) if keep]) # Test invalid indexing - assert_raises(TypeError, SEQ_DATA['seq'].__getitem__, 'abc') + with pytest.raises(TypeError): + SEQ_DATA['seq']['abc'] + #SEQ_DATA['seq'].abc # Get specific columns. seq_view = SEQ_DATA['seq'][:, 2] @@ -285,7 +296,7 @@ def test_arraysequence_setitem(self): # Setitem with a scalar. seq = SEQ_DATA['seq'].copy() seq[:] = 0 - assert_true(seq._data.sum() == 0) + assert seq._data.sum() == 0 # Setitem with a list of ndarray. seq = SEQ_DATA['seq'] * 0 @@ -295,12 +306,12 @@ def test_arraysequence_setitem(self): # Setitem using tuple indexing. seq = ArraySequence(np.arange(900).reshape((50,6,3))) seq[:, 0] = 0 - assert_true(seq._data[:, 0].sum() == 0) + assert seq._data[:, 0].sum() == 0 # Setitem using tuple indexing. seq = ArraySequence(np.arange(900).reshape((50,6,3))) seq[range(len(seq))] = 0 - assert_true(seq._data.sum() == 0) + assert seq._data.sum() == 0 # Setitem of a slice using another slice. seq = ArraySequence(np.arange(900).reshape((50,6,3))) @@ -309,20 +320,26 @@ def test_arraysequence_setitem(self): # Setitem between array sequences with different number of sequences. seq = ArraySequence(np.arange(900).reshape((50,6,3))) - assert_raises(ValueError, seq.__setitem__, slice(0, 4), seq[5:10]) + with pytest.raises(ValueError): + seq.__setitem__(slice(0, 4), seq[5:10]) + # Setitem between array sequences with different amount of points. seq1 = ArraySequence(np.arange(10).reshape(5, 2)) seq2 = ArraySequence(np.arange(15).reshape(5, 3)) - assert_raises(ValueError, seq1.__setitem__, slice(0, 5), seq2) + with pytest.raises(ValueError): + seq1[0:5] = seq2 # Setitem between array sequences with different common shape. seq1 = ArraySequence(np.arange(12).reshape(2, 2, 3)) seq2 = ArraySequence(np.arange(8).reshape(2, 2, 2)) - assert_raises(ValueError, seq1.__setitem__, slice(0, 2), seq2) + + with pytest.raises(ValueError): + seq1[0:2] = seq2 # Invalid index. - assert_raises(TypeError, seq.__setitem__, object(), None) + with pytest.raises(TypeError): + seq.__setitem__(object(), None) def test_arraysequence_operators(self): # Disable division per zero warnings. @@ -341,36 +358,42 @@ def test_arraysequence_operators(self): def _test_unary(op, arrseq): orig = arrseq.copy() seq = getattr(orig, op)() - assert_true(seq is not orig) + assert seq is not orig check_arr_seq(seq, [getattr(d, op)() for d in orig]) def _test_binary(op, arrseq, scalars, seqs, inplace=False): for scalar in scalars: orig = arrseq.copy() seq = getattr(orig, op)(scalar) - assert_true((seq is orig) if inplace else (seq is not orig)) + + assert (seq is orig) == inplace + check_arr_seq(seq, [getattr(e, op)(scalar) for e in arrseq]) # Test math operators with another ArraySequence. for other in seqs: orig = arrseq.copy() seq = getattr(orig, op)(other) - assert_true(seq is not SEQ_DATA['seq']) + assert seq is not SEQ_DATA['seq'] check_arr_seq(seq, [getattr(e1, op)(e2) for e1, e2 in zip(arrseq, other)]) # Operations between array sequences of different lengths. orig = arrseq.copy() - assert_raises(ValueError, getattr(orig, op), orig[::2]) + with pytest.raises(ValueError): + getattr(orig, op)(orig[::2]) # Operations between array sequences with different amount of data. seq1 = ArraySequence(np.arange(10).reshape(5, 2)) seq2 = ArraySequence(np.arange(15).reshape(5, 3)) - assert_raises(ValueError, getattr(seq1, op), seq2) + with pytest.raises(ValueError): + getattr(seq1, op)(seq2) # Operations between array sequences with different common shape. seq1 = ArraySequence(np.arange(12).reshape(2, 2, 3)) seq2 = ArraySequence(np.arange(8).reshape(2, 2, 2)) - assert_raises(ValueError, getattr(seq1, op), seq2) + with pytest.raises(ValueError): + getattr(seq1, op)(seq2) + for op in ["__add__", "__sub__", "__mul__", "__mod__", @@ -392,24 +415,36 @@ def _test_binary(op, arrseq, scalars, seqs, inplace=False): continue # Going to deal with it separately. _test_binary(op, seq_int, [42, -3, True, 0], [seq_int, seq_bool, -seq_int], inplace=True) # int <-- int - assert_raises(TypeError, _test_binary, op, seq_int, [0.5], [], inplace=True) # int <-- float - assert_raises(TypeError, _test_binary, op, seq_int, [], [seq], inplace=True) # int <-- float + + with pytest.raises(TypeError): + _test_binary(op, seq_int, [0.5], [], inplace=True) # int <-- float + with pytest.raises(TypeError): + _test_binary(op, seq_int, [], [seq], inplace=True) # int <-- float + # __pow__ : Integers to negative integer powers are not allowed. _test_binary("__pow__", seq, [42, -3, True, 0], [seq_int, seq_bool, -seq_int]) _test_binary("__ipow__", seq, [42, -3, True, 0], [seq_int, seq_bool, -seq_int], inplace=True) - assert_raises(ValueError, _test_binary, "__pow__", seq_int, [-3], []) - assert_raises(ValueError, _test_binary, "__ipow__", seq_int, [-3], [], inplace=True) - + + with pytest.raises(ValueError): + _test_binary("__pow__", seq_int, [-3], []) + with pytest.raises(ValueError): + _test_binary("__ipow__", seq_int, [-3], [], inplace=True) + # __itruediv__ is only valid with float arrseq. for scalar in SCALARS + ARRSEQS: - assert_raises(TypeError, getattr(seq_int.copy(), "__itruediv__"), scalar) + seq_int_cp = seq_int.copy() + with pytest.raises(TypeError): + seq_int_cp /= scalar # Bitwise operators for op in ("__lshift__", "__rshift__", "__or__", "__and__", "__xor__"): _test_binary(op, seq_bool, [42, -3, True, 0], [seq_int, seq_bool, -seq_int]) - assert_raises(TypeError, _test_binary, op, seq_bool, [0.5], []) - assert_raises(TypeError, _test_binary, op, seq, [], [seq]) + + with pytest.raises(TypeError): + _test_binary(op, seq_bool, [0.5], []) + with pytest.raises(TypeError): + _test_binary(op, seq, [], [seq]) # Unary operators for op in ["__neg__", "__abs__"]: @@ -420,7 +455,8 @@ def _test_binary(op, arrseq, scalars, seqs, inplace=False): _test_unary("__abs__", seq_bool) _test_unary("__invert__", seq_bool) - assert_raises(TypeError, _test_unary, "__invert__", seq) + with pytest.raises(TypeError): + _test_unary("__invert__", seq) # Restore flags. np.seterr(**flags) @@ -440,7 +476,7 @@ def test_arraysequence_repr(self): txt1 = repr(seq) np.set_printoptions(threshold=nb_arrays//2) txt2 = repr(seq) - assert_true(len(txt2) < len(txt1)) + assert len(txt2) < len(txt1) np.set_printoptions(threshold=bkp_threshold) def test_save_and_load_arraysequence(self): @@ -483,10 +519,10 @@ def test_concatenate(): new_seq = concatenate(seqs, axis=1) seq._data += 100 # Modifying the 'seq' shouldn't change 'new_seq'. check_arr_seq(new_seq, SEQ_DATA['data']) - assert_true(not new_seq._is_view) + assert new_seq._is_view is not True seq = SEQ_DATA['seq'] seqs = [seq[:, [i]] for i in range(seq.common_shape[0])] new_seq = concatenate(seqs, axis=0) - assert_true(len(new_seq), seq.common_shape[0] * len(seq)) + assert len(new_seq) == seq.common_shape[0] * len(seq) assert_array_equal(new_seq._data, seq._data.T.reshape((-1, 1))) diff --git a/nibabel/streamlines/tests/test_tractogram.py b/nibabel/streamlines/tests/test_tractogram.py index 407f3ef413..e09a7d83e2 100644 --- a/nibabel/streamlines/tests/test_tractogram.py +++ b/nibabel/streamlines/tests/test_tractogram.py @@ -6,9 +6,8 @@ import operator from collections import defaultdict -from nibabel.testing import assert_arrays_equal -from nibabel.testing import clear_and_catch_warnings -from nose.tools import assert_equal, assert_raises, assert_true +import pytest +from ....testing_pytest import assert_arrays_equal, clear_and_catch_warnings from numpy.testing import assert_array_equal, assert_array_almost_equal from .. import tractogram as module_tractogram @@ -93,7 +92,7 @@ def make_dummy_streamline(nb_points): return streamline, data_per_point, data_for_streamline -def setup(): +def setup_module(): global DATA DATA['rng'] = np.random.RandomState(1234) @@ -149,13 +148,12 @@ def check_tractogram_item(tractogram_item, assert_array_equal(tractogram_item.streamline, streamline) - assert_equal(len(tractogram_item.data_for_streamline), - len(data_for_streamline)) + assert len(tractogram_item.data_for_streamline) == len(data_for_streamline) for key in data_for_streamline.keys(): assert_array_equal(tractogram_item.data_for_streamline[key], data_for_streamline[key]) - assert_equal(len(tractogram_item.data_for_points), len(data_for_points)) + assert len(tractogram_item.data_for_points) == len(data_for_points) for key in data_for_points.keys(): assert_arrays_equal(tractogram_item.data_for_points[key], data_for_points[key]) @@ -171,16 +169,16 @@ def check_tractogram(tractogram, data_per_streamline={}, data_per_point={}): streamlines = list(streamlines) - assert_equal(len(tractogram), len(streamlines)) + assert len(tractogram) == len(streamlines) assert_arrays_equal(tractogram.streamlines, streamlines) [t for t in tractogram] # Force iteration through tractogram. - assert_equal(len(tractogram.data_per_streamline), len(data_per_streamline)) + assert len(tractogram.data_per_streamline) == len(data_per_streamline) for key in data_per_streamline.keys(): assert_arrays_equal(tractogram.data_per_streamline[key], data_per_streamline[key]) - assert_equal(len(tractogram.data_per_point), len(data_per_point)) + assert len(tractogram.data_per_point) == len(data_per_point) for key in data_per_point.keys(): assert_arrays_equal(tractogram.data_per_point[key], data_per_point[key]) @@ -204,43 +202,44 @@ def test_per_array_dict_creation(self): nb_streamlines = len(DATA['tractogram']) data_per_streamline = DATA['tractogram'].data_per_streamline data_dict = PerArrayDict(nb_streamlines, data_per_streamline) - assert_equal(data_dict.keys(), data_per_streamline.keys()) + assert data_dict.keys() == data_per_streamline.keys() for k in data_dict.keys(): assert_array_equal(data_dict[k], data_per_streamline[k]) del data_dict['mean_curvature'] - assert_equal(len(data_dict), - len(data_per_streamline)-1) + assert len(data_dict) == len(data_per_streamline) - 1 # Create a PerArrayDict object using an existing dict object. data_per_streamline = DATA['data_per_streamline'] data_dict = PerArrayDict(nb_streamlines, data_per_streamline) - assert_equal(data_dict.keys(), data_per_streamline.keys()) + assert data_dict.keys() == data_per_streamline.keys() for k in data_dict.keys(): assert_array_equal(data_dict[k], data_per_streamline[k]) del data_dict['mean_curvature'] - assert_equal(len(data_dict), len(data_per_streamline)-1) + assert len(data_dict) == len(data_per_streamline) - 1 # Create a PerArrayDict object using keyword arguments. data_per_streamline = DATA['data_per_streamline'] data_dict = PerArrayDict(nb_streamlines, **data_per_streamline) - assert_equal(data_dict.keys(), data_per_streamline.keys()) + assert data_dict.keys() == data_per_streamline.keys() for k in data_dict.keys(): assert_array_equal(data_dict[k], data_per_streamline[k]) del data_dict['mean_curvature'] - assert_equal(len(data_dict), len(data_per_streamline)-1) + assert len(data_dict) == len(data_per_streamline) - 1 def test_getitem(self): sdict = PerArrayDict(len(DATA['tractogram']), DATA['data_per_streamline']) - assert_raises(KeyError, sdict.__getitem__, 'invalid') + with pytest.raises(KeyError): + sdict['invalid'] + #assert_raises(KeyError, sdict.__getitem__, 'invalid') # Test slicing and advanced indexing. for k, v in DATA['tractogram'].data_per_streamline.items(): - assert_true(k in sdict) + assert k in sdict assert_arrays_equal(sdict[k], v) assert_arrays_equal(sdict[::2][k], v[::2]) assert_arrays_equal(sdict[::-1][k], v[::-1]) @@ -258,7 +257,7 @@ def test_extend(self): new_data) sdict.extend(sdict2) - assert_equal(len(sdict), len(sdict2)) + assert len(sdict) == len(sdict2) for k in DATA['tractogram'].data_per_streamline: assert_arrays_equal(sdict[k][:len(DATA['tractogram'])], DATA['tractogram'].data_per_streamline[k]) @@ -278,21 +277,24 @@ def test_extend(self): 'mean_colors': 4 * np.array(DATA['mean_colors']), 'other': 5 * np.array(DATA['mean_colors'])} sdict2 = PerArrayDict(len(DATA['tractogram']), new_data) - assert_raises(ValueError, sdict.extend, sdict2) + with pytest.raises(ValueError): + sdict.extend(sdict2) # Other dict has not the same entries (key mistmached). new_data = {'mean_curvature': 2 * np.array(DATA['mean_curvature']), 'mean_torsion': 3 * np.array(DATA['mean_torsion']), 'other': 4 * np.array(DATA['mean_colors'])} sdict2 = PerArrayDict(len(DATA['tractogram']), new_data) - assert_raises(ValueError, sdict.extend, sdict2) + with pytest.raises(ValueError): + sdict.extend(sdict2) # Other dict has the right number of entries but wrong shape. new_data = {'mean_curvature': 2 * np.array(DATA['mean_curvature']), 'mean_torsion': 3 * np.array(DATA['mean_torsion']), 'mean_colors': 4 * np.array(DATA['mean_torsion'])} sdict2 = PerArrayDict(len(DATA['tractogram']), new_data) - assert_raises(ValueError, sdict.extend, sdict2) + with pytest.raises(ValueError): + sdict.extend(sdict2) class TestPerArraySequenceDict(unittest.TestCase): @@ -303,43 +305,44 @@ def test_per_array_sequence_dict_creation(self): total_nb_rows = DATA['tractogram'].streamlines.total_nb_rows data_per_point = DATA['tractogram'].data_per_point data_dict = PerArraySequenceDict(total_nb_rows, data_per_point) - assert_equal(data_dict.keys(), data_per_point.keys()) + assert data_dict.keys() == data_per_point.keys() for k in data_dict.keys(): assert_arrays_equal(data_dict[k], data_per_point[k]) del data_dict['fa'] - assert_equal(len(data_dict), - len(data_per_point)-1) + assert len(data_dict) == len(data_per_point) - 1 # Create a PerArraySequenceDict object using an existing dict object. data_per_point = DATA['data_per_point'] data_dict = PerArraySequenceDict(total_nb_rows, data_per_point) - assert_equal(data_dict.keys(), data_per_point.keys()) + assert data_dict.keys() == data_per_point.keys() for k in data_dict.keys(): assert_arrays_equal(data_dict[k], data_per_point[k]) del data_dict['fa'] - assert_equal(len(data_dict), len(data_per_point)-1) + assert len(data_dict) == len(data_per_point) - 1 # Create a PerArraySequenceDict object using keyword arguments. data_per_point = DATA['data_per_point'] data_dict = PerArraySequenceDict(total_nb_rows, **data_per_point) - assert_equal(data_dict.keys(), data_per_point.keys()) + assert data_dict.keys() == data_per_point.keys() for k in data_dict.keys(): assert_arrays_equal(data_dict[k], data_per_point[k]) del data_dict['fa'] - assert_equal(len(data_dict), len(data_per_point)-1) + assert len(data_dict) == len(data_per_point) - 1 def test_getitem(self): total_nb_rows = DATA['tractogram'].streamlines.total_nb_rows sdict = PerArraySequenceDict(total_nb_rows, DATA['data_per_point']) - assert_raises(KeyError, sdict.__getitem__, 'invalid') + with pytest.raises(KeyError): + sdict['invalid'] + #assert_raises(KeyError, sdict.__getitem__, 'invalid') # Test slicing and advanced indexing. for k, v in DATA['tractogram'].data_per_point.items(): - assert_true(k in sdict) + assert k in sdict assert_arrays_equal(sdict[k], v) assert_arrays_equal(sdict[::2][k], v[::2]) assert_arrays_equal(sdict[::-1][k], v[::-1]) @@ -360,7 +363,7 @@ def test_extend(self): sdict2 = PerArraySequenceDict(np.sum(list_nb_points), new_data) sdict.extend(sdict2) - assert_equal(len(sdict), len(sdict2)) + assert len(sdict) == len(sdict2) for k in DATA['tractogram'].data_per_point: assert_arrays_equal(sdict[k][:len(DATA['tractogram'])], DATA['tractogram'].data_per_point[k]) @@ -382,7 +385,8 @@ def test_extend(self): data_per_point_shapes, rng=DATA['rng']) sdict2 = PerArraySequenceDict(np.sum(list_nb_points), new_data) - assert_raises(ValueError, sdict.extend, sdict2) + with pytest.raises(ValueError): + sdict.extend(sdict2) # Other dict has not the same entries (key mistmached). data_per_point_shapes = {"colors": DATA['colors'][0].shape[1:], @@ -391,7 +395,8 @@ def test_extend(self): data_per_point_shapes, rng=DATA['rng']) sdict2 = PerArraySequenceDict(np.sum(list_nb_points), new_data) - assert_raises(ValueError, sdict.extend, sdict2) + with pytest.raises(ValueError): + sdict.extend(sdict2) # Other dict has the right number of entries but wrong shape. data_per_point_shapes = {"colors": DATA['colors'][0].shape[1:], @@ -400,7 +405,8 @@ def test_extend(self): data_per_point_shapes, rng=DATA['rng']) sdict2 = PerArraySequenceDict(np.sum(list_nb_points), new_data) - assert_raises(ValueError, sdict.extend, sdict2) + with pytest.raises(ValueError): + sdict.extend(sdict2) class TestLazyDict(unittest.TestCase): @@ -413,14 +419,13 @@ def test_lazydict_creation(self): expected_keys = DATA['data_per_streamline_func'].keys() for data_dict in lazy_dicts: - assert_true(is_lazy_dict(data_dict)) - assert_equal(data_dict.keys(), expected_keys) + assert is_lazy_dict(data_dict) + assert data_dict.keys() == expected_keys for k in data_dict.keys(): assert_array_equal(list(data_dict[k]), list(DATA['data_per_streamline'][k])) - assert_equal(len(data_dict), - len(DATA['data_per_streamline_func'])) + assert len(data_dict) == len(DATA['data_per_streamline_func']) class TestTractogramItem(unittest.TestCase): @@ -439,7 +444,7 @@ def test_creating_tractogram_item(self): # Create a tractogram item with a streamline, data. t = TractogramItem(streamline, data_for_streamline, data_for_points) - assert_equal(len(t), len(streamline)) + assert len(t) == len(streamline) assert_array_equal(t.streamline, streamline) assert_array_equal(list(t), streamline) assert_array_equal(t.data_for_streamline['mean_curvature'], @@ -456,7 +461,7 @@ def test_tractogram_creation(self): # Create an empty tractogram. tractogram = Tractogram() check_tractogram(tractogram) - assert_true(tractogram.affine_to_rasmm is None) + assert tractogram.affine_to_rasmm is None # Create a tractogram with only streamlines tractogram = Tractogram(streamlines=DATA['streamlines']) @@ -477,8 +482,8 @@ def test_tractogram_creation(self): DATA['data_per_streamline'], DATA['data_per_point']) - assert_true(is_data_dict(tractogram.data_per_streamline)) - assert_true(is_data_dict(tractogram.data_per_point)) + assert is_data_dict(tractogram.data_per_streamline) + assert is_data_dict(tractogram.data_per_point) # Create a tractogram from another tractogram attributes. tractogram2 = Tractogram(tractogram.streamlines, @@ -502,8 +507,9 @@ def test_tractogram_creation(self): [(0, 0, 1)]*5] data_per_point = {'wrong_data': wrong_data} - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_point=data_per_point) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], + data_per_point=data_per_point) # Inconsistent number of scalars between streamlines wrong_data = [[(1, 0, 0)]*1, @@ -511,8 +517,9 @@ def test_tractogram_creation(self): [(0, 0, 1)]*5] data_per_point = {'wrong_data': wrong_data} - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_point=data_per_point) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], + data_per_point=data_per_point) def test_setting_affine_to_rasmm(self): tractogram = DATA['tractogram'].copy() @@ -520,19 +527,20 @@ def test_setting_affine_to_rasmm(self): # Test assigning None. tractogram.affine_to_rasmm = None - assert_true(tractogram.affine_to_rasmm is None) + assert tractogram.affine_to_rasmm is None # Test assigning a valid ndarray (should make a copy). tractogram.affine_to_rasmm = affine - assert_true(tractogram.affine_to_rasmm is not affine) + assert tractogram.affine_to_rasmm is not affine # Test assigning a list of lists. tractogram.affine_to_rasmm = affine.tolist() assert_array_equal(tractogram.affine_to_rasmm, affine) # Test assigning a ndarray with wrong shape. - assert_raises(ValueError, setattr, tractogram, - "affine_to_rasmm", affine[::2]) + with pytest.raises(ValueError): + tractogram.affine_to_rasmm = affine[::2] + def test_tractogram_getitem(self): # Retrieve TractogramItem by their index. @@ -593,21 +601,16 @@ def test_tractogram_copy(self): tractogram = DATA['tractogram'].copy() # Check we copied the data and not simply created new references. - assert_true(tractogram is not DATA['tractogram']) - assert_true(tractogram.streamlines - is not DATA['tractogram'].streamlines) - assert_true(tractogram.data_per_streamline - is not DATA['tractogram'].data_per_streamline) - assert_true(tractogram.data_per_point - is not DATA['tractogram'].data_per_point) + assert tractogram is not DATA['tractogram'] + assert tractogram.streamlines is not DATA['tractogram'].streamlines + assert tractogram.data_per_streamline is not DATA['tractogram'].data_per_streamline + assert tractogram.data_per_point is not DATA['tractogram'].data_per_point for key in tractogram.data_per_streamline: - assert_true(tractogram.data_per_streamline[key] - is not DATA['tractogram'].data_per_streamline[key]) + assert tractogram.data_per_streamline[key] is not DATA['tractogram'].data_per_streamline[key] for key in tractogram.data_per_point: - assert_true(tractogram.data_per_point[key] - is not DATA['tractogram'].data_per_point[key]) + assert tractogram.data_per_point[key] is not DATA['tractogram'].data_per_point[key] # Check the values of the data are the same. assert_tractogram_equal(tractogram, DATA['tractogram']) @@ -618,39 +621,44 @@ def test_creating_invalid_tractogram(self): [(0, 1, 0)]*2, [(0, 0, 1)]*3] # Last streamlines has 5 points. - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_point={'scalars': scalars}) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], + data_per_point={'scalars':scalars}) # Not enough data_per_streamline for all streamlines. properties = [np.array([1.11, 1.22], dtype="f4"), np.array([3.11, 3.22], dtype="f4")] - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_streamline={'properties': properties}) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], + data_per_streamline={'properties': properties}) # Inconsistent dimension for a data_per_point. scalars = [[(1, 0, 0)]*1, [(0, 1)]*2, [(0, 0, 1)]*5] - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_point={'scalars': scalars}) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], + data_per_point={'scalars':scalars}) # Inconsistent dimension for a data_per_streamline. properties = [[1.11, 1.22], [2.11], [3.11, 3.22]] - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_streamline={'properties': properties}) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], + data_per_streamline={'properties': properties}) # Too many dimension for a data_per_streamline. properties = [np.array([[1.11], [1.22]], dtype="f4"), np.array([[2.11], [2.22]], dtype="f4"), np.array([[3.11], [3.22]], dtype="f4")] - assert_raises(ValueError, Tractogram, DATA['streamlines'], - data_per_streamline={'properties': properties}) + with pytest.raises(ValueError): + Tractogram(streamlines=DATA['streamlines'], + data_per_streamline={'properties': properties}) def test_tractogram_apply_affine(self): tractogram = DATA['tractogram'].copy() @@ -660,7 +668,7 @@ def test_tractogram_apply_affine(self): # Apply the affine to the streamline in a lazy manner. transformed_tractogram = tractogram.apply_affine(affine, lazy=True) - assert_true(type(transformed_tractogram) is LazyTractogram) + assert type(transformed_tractogram) is LazyTractogram check_tractogram(transformed_tractogram, streamlines=[s*scaling for s in DATA['streamlines']], data_per_streamline=DATA['data_per_streamline'], @@ -673,7 +681,7 @@ def test_tractogram_apply_affine(self): # Apply the affine to the streamlines in-place. transformed_tractogram = tractogram.apply_affine(affine) - assert_true(transformed_tractogram is tractogram) + assert transformed_tractogram is tractogram check_tractogram(tractogram, streamlines=[s*scaling for s in DATA['streamlines']], data_per_streamline=DATA['data_per_streamline'], @@ -689,7 +697,7 @@ def test_tractogram_apply_affine(self): # shouldn't affect the remaining streamlines. tractogram = DATA['tractogram'].copy() transformed_tractogram = tractogram[::2].apply_affine(affine) - assert_true(transformed_tractogram is not tractogram) + assert transformed_tractogram is not tractogram check_tractogram(tractogram[::2], streamlines=[s*scaling for s in DATA['streamlines'][::2]], data_per_streamline=DATA['tractogram'].data_per_streamline[::2], @@ -723,7 +731,7 @@ def test_tractogram_apply_affine(self): tractogram = DATA['tractogram'].copy() tractogram.affine_to_rasmm = None tractogram.apply_affine(affine) - assert_true(tractogram.affine_to_rasmm is None) + assert tractogram.affine_to_rasmm is None def test_tractogram_to_world(self): tractogram = DATA['tractogram'].copy() @@ -737,7 +745,7 @@ def test_tractogram_to_world(self): np.linalg.inv(affine)) tractogram_world = transformed_tractogram.to_world(lazy=True) - assert_true(type(tractogram_world) is LazyTractogram) + assert type(tractogram_world) is LazyTractogram assert_array_almost_equal(tractogram_world.affine_to_rasmm, np.eye(4)) for s1, s2 in zip(tractogram_world.streamlines, DATA['streamlines']): @@ -745,14 +753,14 @@ def test_tractogram_to_world(self): # Bring them back streamlines to world space in a in-place manner. tractogram_world = transformed_tractogram.to_world() - assert_true(tractogram_world is tractogram) + assert tractogram_world is tractogram assert_array_almost_equal(tractogram.affine_to_rasmm, np.eye(4)) for s1, s2 in zip(tractogram.streamlines, DATA['streamlines']): assert_array_almost_equal(s1, s2) # Calling to_world twice should do nothing. tractogram_world2 = transformed_tractogram.to_world() - assert_true(tractogram_world2 is tractogram) + assert tractogram_world2 is tractogram assert_array_almost_equal(tractogram.affine_to_rasmm, np.eye(4)) for s1, s2 in zip(tractogram.streamlines, DATA['streamlines']): assert_array_almost_equal(s1, s2) @@ -760,7 +768,8 @@ def test_tractogram_to_world(self): # Calling to_world when affine_to_rasmm is None should fail. tractogram = DATA['tractogram'].copy() tractogram.affine_to_rasmm = None - assert_raises(ValueError, tractogram.to_world) + with pytest.raises(ValueError): + tractogram.to_world() def test_tractogram_extend(self): # Load tractogram that contains some metadata. @@ -770,7 +779,7 @@ def test_tractogram_extend(self): (extender, True)): first_arg = t.copy() new_t = op(first_arg, t) - assert_equal(new_t is first_arg, in_place) + assert (new_t is first_arg) == in_place assert_tractogram_equal(new_t[:len(t)], DATA['tractogram']) assert_tractogram_equal(new_t[len(t):], DATA['tractogram']) @@ -789,7 +798,8 @@ class TestLazyTractogram(unittest.TestCase): def test_lazy_tractogram_creation(self): # To create tractogram from arrays use `Tractogram`. - assert_raises(TypeError, LazyTractogram, DATA['streamlines']) + with pytest.raises(TypeError): + LazyTractogram(streamlines=DATA['streamlines']) # Streamlines and other data as generators streamlines = (x for x in DATA['streamlines']) @@ -800,29 +810,34 @@ def test_lazy_tractogram_creation(self): # Creating LazyTractogram with generators is not allowed as # generators get exhausted and are not reusable unlike generator # function. - assert_raises(TypeError, LazyTractogram, streamlines) - assert_raises(TypeError, LazyTractogram, - data_per_point={"none": None}) - assert_raises(TypeError, LazyTractogram, - data_per_streamline=data_per_streamline) - assert_raises(TypeError, LazyTractogram, DATA['streamlines'], - data_per_point=data_per_point) + with pytest.raises(TypeError): + LazyTractogram(streamlines=streamlines) + + with pytest.raises(TypeError): + LazyTractogram(data_per_point={"none": None}) + + with pytest.raises(TypeError): + LazyTractogram(data_per_streamline=data_per_streamline) + + with pytest.raises(TypeError): + LazyTractogram(streamlines=DATA['streamlines'], + data_per_point=data_per_point) # Empty `LazyTractogram` tractogram = LazyTractogram() check_tractogram(tractogram) - assert_true(tractogram.affine_to_rasmm is None) + assert tractogram.affine_to_rasmm is None # Create tractogram with streamlines and other data tractogram = LazyTractogram(DATA['streamlines_func'], DATA['data_per_streamline_func'], DATA['data_per_point_func']) - assert_true(is_lazy_dict(tractogram.data_per_streamline)) - assert_true(is_lazy_dict(tractogram.data_per_point)) + assert is_lazy_dict(tractogram.data_per_streamline) + assert is_lazy_dict(tractogram.data_per_point) [t for t in tractogram] # Force iteration through tractogram. - assert_equal(len(tractogram), len(DATA['streamlines'])) + assert len(tractogram) == len(DATA['streamlines']) # Generator functions get re-called and creates new iterators. for i in range(2): @@ -854,18 +869,20 @@ def _data_gen(): assert_tractogram_equal(tractogram, DATA['tractogram']) # Creating a LazyTractogram from not a corouting should raise an error. - assert_raises(TypeError, LazyTractogram.from_data_func, _data_gen()) + with pytest.raises(TypeError): + LazyTractogram.from_data_func(_data_gen()) def test_lazy_tractogram_getitem(self): - assert_raises(NotImplementedError, - DATA['lazy_tractogram'].__getitem__, 0) + with pytest.raises(NotImplementedError): + DATA['lazy_tractogram'][0] def test_lazy_tractogram_extend(self): t = DATA['lazy_tractogram'].copy() new_t = DATA['lazy_tractogram'].copy() for op in (operator.add, operator.iadd, extender): - assert_raises(NotImplementedError, op, new_t, t) + with pytest.raises(NotImplementedError): + op(new_t, t) def test_lazy_tractogram_len(self): modules = [module_tractogram] # Modules for which to catch warnings. @@ -874,35 +891,35 @@ def test_lazy_tractogram_len(self): # Calling `len` will create new generators each time. tractogram = LazyTractogram(DATA['streamlines_func']) - assert_true(tractogram._nb_streamlines is None) + assert tractogram._nb_streamlines is None # This should produce a warning message. - assert_equal(len(tractogram), len(DATA['streamlines'])) - assert_equal(tractogram._nb_streamlines, len(DATA['streamlines'])) - assert_equal(len(w), 1) + assert len(tractogram) == len(DATA['streamlines']) + assert tractogram._nb_streamlines == len(DATA['streamlines']) + assert len(w) == 1 tractogram = LazyTractogram(DATA['streamlines_func']) # New instances should still produce a warning message. - assert_equal(len(tractogram), len(DATA['streamlines'])) - assert_equal(len(w), 2) - assert_true(issubclass(w[-1].category, Warning)) + assert len(tractogram) == len(DATA['streamlines']) + assert len(w) == 2 + assert issubclass(w[-1].category, Warning) is True # Calling again 'len' again should *not* produce a warning. - assert_equal(len(tractogram), len(DATA['streamlines'])) - assert_equal(len(w), 2) + assert len(tractogram) == len(DATA['streamlines']) + assert len(w) == 2 with clear_and_catch_warnings(record=True, modules=modules) as w: # Once we iterated through the tractogram, we know the length. tractogram = LazyTractogram(DATA['streamlines_func']) - assert_true(tractogram._nb_streamlines is None) + assert tractogram._nb_streamlines is None [t for t in tractogram] # Force iteration through tractogram. - assert_equal(tractogram._nb_streamlines, len(DATA['streamlines'])) + assert tractogram._nb_streamlines == len(DATA['streamlines']) # This should *not* produce a warning. - assert_equal(len(tractogram), len(DATA['streamlines'])) - assert_equal(len(w), 0) + assert len(tractogram) == len(DATA['streamlines']) + assert len(w) == 0 def test_lazy_tractogram_apply_affine(self): affine = np.eye(4) @@ -912,7 +929,7 @@ def test_lazy_tractogram_apply_affine(self): tractogram = DATA['lazy_tractogram'].copy() transformed_tractogram = tractogram.apply_affine(affine) - assert_true(transformed_tractogram is not tractogram) + assert transformed_tractogram is not tractogram assert_array_equal(tractogram._affine_to_apply, np.eye(4)) assert_array_equal(tractogram.affine_to_rasmm, np.eye(4)) assert_array_equal(transformed_tractogram._affine_to_apply, affine) @@ -934,14 +951,15 @@ def test_lazy_tractogram_apply_affine(self): # Calling to_world when affine_to_rasmm is None should fail. tractogram = DATA['lazy_tractogram'].copy() tractogram.affine_to_rasmm = None - assert_raises(ValueError, tractogram.to_world) + with pytest.raises(ValueError): + tractogram.to_world() # But calling apply_affine when affine_to_rasmm is None should work. tractogram = DATA['lazy_tractogram'].copy() tractogram.affine_to_rasmm = None transformed_tractogram = tractogram.apply_affine(affine) assert_array_equal(transformed_tractogram._affine_to_apply, affine) - assert_true(transformed_tractogram.affine_to_rasmm is None) + assert transformed_tractogram.affine_to_rasmm is None check_tractogram(transformed_tractogram, streamlines=[s*scaling for s in DATA['streamlines']], data_per_streamline=DATA['data_per_streamline'], @@ -949,8 +967,9 @@ def test_lazy_tractogram_apply_affine(self): # Calling apply_affine with lazy=False should fail for LazyTractogram. tractogram = DATA['lazy_tractogram'].copy() - assert_raises(ValueError, tractogram.apply_affine, - affine=np.eye(4), lazy=False) + with pytest.raises(ValueError): + tractogram.apply_affine(affine=np.eye(4), lazy=False) + def test_tractogram_to_world(self): tractogram = DATA['lazy_tractogram'].copy() @@ -964,7 +983,7 @@ def test_tractogram_to_world(self): np.linalg.inv(affine)) tractogram_world = transformed_tractogram.to_world() - assert_true(tractogram_world is not transformed_tractogram) + assert tractogram_world is not transformed_tractogram assert_array_almost_equal(tractogram_world.affine_to_rasmm, np.eye(4)) for s1, s2 in zip(tractogram_world.streamlines, DATA['streamlines']): @@ -979,40 +998,37 @@ def test_tractogram_to_world(self): # Calling to_world when affine_to_rasmm is None should fail. tractogram = DATA['lazy_tractogram'].copy() tractogram.affine_to_rasmm = None - assert_raises(ValueError, tractogram.to_world) + with pytest.raises(ValueError): + tractogram.to_world() def test_lazy_tractogram_copy(self): # Create a copy of the lazy tractogram. tractogram = DATA['lazy_tractogram'].copy() # Check we copied the data and not simply created new references. - assert_true(tractogram is not DATA['lazy_tractogram']) + assert tractogram is not DATA['lazy_tractogram'] # When copying LazyTractogram, the generator function yielding # streamlines should stay the same. - assert_true(tractogram._streamlines - is DATA['lazy_tractogram']._streamlines) + assert tractogram._streamlines is DATA['lazy_tractogram']._streamlines # Copying LazyTractogram, creates new internal LazyDict objects, # but generator functions contained in it should stay the same. - assert_true(tractogram._data_per_streamline - is not DATA['lazy_tractogram']._data_per_streamline) - assert_true(tractogram._data_per_point - is not DATA['lazy_tractogram']._data_per_point) + assert tractogram._data_per_streamline is not DATA['lazy_tractogram']._data_per_streamline + assert tractogram._data_per_point is not DATA['lazy_tractogram']._data_per_point for key in tractogram.data_per_streamline: data = tractogram.data_per_streamline.store[key] expected = DATA['lazy_tractogram'].data_per_streamline.store[key] - assert_true(data is expected) + assert data is expected for key in tractogram.data_per_point: data = tractogram.data_per_point.store[key] expected = DATA['lazy_tractogram'].data_per_point.store[key] - assert_true(data is expected) + assert data is expected # The affine should be a copy. - assert_true(tractogram._affine_to_apply - is not DATA['lazy_tractogram']._affine_to_apply) + assert tractogram._affine_to_apply is not DATA['lazy_tractogram']._affine_to_apply assert_array_equal(tractogram._affine_to_apply, DATA['lazy_tractogram']._affine_to_apply)