test_wrapperutils.py 28.6 KB
Newer Older
1
2
3
4
5
6
7
#!/usr/bin/env python
#
# test_wrapperutils.py -
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#

8
9
10
import os.path as op
import            os
import            shlex
11
import            pathlib
12
13
import            textwrap

14
from unittest import mock
15
16
17

import pytest

18
19
20
21
import numpy as np
import nibabel as nib

import fsl.utils.tempdir         as tempdir
22
import fsl.utils.run             as run
23
import fsl.utils.assertions      as asrt
24
import fsl.utils.fslsub          as fslsub
25
import fsl.data.image            as fslimage
26
27
28
import fsl.wrappers.wrapperutils as wutils


29
from .. import mockFSLDIR, cleardir, checkdir, testdir, touch
30
from ..test_run import mock_fsl_sub
31
32


33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
def test_applyArgStyle():

    kwargs = {
        'name'  : 'val',
        'name2' : ['val1', 'val2'],
    }

    # these combinations of style+valsep should
    # raise an error
    with pytest.raises(ValueError):
        wutils.applyArgStyle(style='-=',  valsep=' ', **kwargs)
    with pytest.raises(ValueError):
        wutils.applyArgStyle(style='--=', valsep=' ', **kwargs)

    # unsupported style/valsep
    with pytest.raises(ValueError):
        wutils.applyArgStyle('?', **kwargs)
    with pytest.raises(ValueError):
        wutils.applyArgStyle('-', valsep='b', **kwargs)

    # style, valsep, expected_result.
    # Order of arguments is not guaranteed
    tests = [
        ('-',   ' ', [' -name  val', '-name2   val1 val2']),
        ('-',   '"', [' -name  val', '-name2  "val1 val2"']),
        ('-',   ',', [' -name  val', '-name2   val1,val2']),

        ('--',  ' ', ['--name  val', '--name2  val1 val2']),
        ('--',  '"', ['--name  val', '--name2 "val1 val2"']),
        ('--',  ',', ['--name  val', '--name2  val1,val2']),

        ('-=',  '"', [' -name=val', '-name2="val1 val2"']),
        ('-=',  ',', [' -name=val', '-name2=val1,val2']),

        ('--=', '"', ['--name=val', '--name2="val1 val2"']),
        ('--=', ',', ['--name=val', '--name2=val1,val2']),
    ]

    for style, valsep, exp in tests:
        exp    = [shlex.split(e) for e in exp]
        result = wutils.applyArgStyle(style, valsep=valsep, **kwargs)

        assert result in (exp[0] + exp[1], exp[1] + exp[0])


def test_applyArgStyle_argmap():

    kwargs = {
        'name1' : 'val1',
        'name2' : 'val2',
    }

    argmap = {
        'name1' : 'n',
        'name2' : 'm',
    }

    # order not guaranteed
    exp = [shlex.split('-n val1 -m val2'),
           shlex.split('-m val2 -n val1')]

    assert wutils.applyArgStyle('-', argmap=argmap, **kwargs) in exp


def test_applyArgStyle_valmap():

    valmap = {
        'a' : wutils.SHOW_IF_TRUE,
        'b' : wutils.HIDE_IF_TRUE,
    }

    # kwargs, expected
    tests = [
        ({                          }, ['']),
        ({ 'a' : False,             }, ['']),
        ({ 'a' : True,              }, ['-a']),
        ({              'b' : False }, ['-b']),
        ({              'b' : True  }, ['']),
        ({ 'a' : False, 'b' : True  }, ['']),
        ({ 'a' : True,  'b' : True  }, ['-a']),
        ({ 'a' : False, 'b' : False }, ['-b']),
        ({ 'a' : False, 'b' : True  }, ['']),
        ({ 'a' : True,  'b' : False }, ['-a -b', '-b -a']),
        ({ 'a' : True,  'b' : True  }, ['-a']),
    ]

    for kwargs, expected in tests:
        expected = [shlex.split(e) for e in expected]
        assert wutils.applyArgStyle('-', valmap=valmap, **kwargs) in expected


def test_applyArgStyle_argmap_valmap():

    argmap = {'a1' : 'a', 'a2' : 'b'}
    valmap = {
        'a' : wutils.SHOW_IF_TRUE,
        'b' : wutils.HIDE_IF_TRUE,
    }

    # kwargs, expected
    tests = [
        ({                            }, ['']),
        ({ 'a1' : False,              }, ['']),
        ({ 'a1' : True,               }, ['-a']),
        ({               'a2' : False }, ['-b']),
        ({               'a2' : True  }, ['']),
        ({ 'a1' : False, 'a2' : True  }, ['']),
        ({ 'a1' : True,  'a2' : True  }, ['-a']),
        ({ 'a1' : False, 'a2' : False }, ['-b']),
        ({ 'a1' : False, 'a2' : True  }, ['']),
        ({ 'a1' : True,  'a2' : False }, ['-a -b', '-b -a']),
        ({ 'a1' : True,  'a2' : True  }, ['-a']),
    ]

    for kwargs, expected in tests:
        expected = [shlex.split(e) for e in expected]
        assert wutils.applyArgStyle(
            '-', argmap=argmap, valmap=valmap, **kwargs) in expected


Paul McCarthy's avatar
Paul McCarthy committed
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
def test_namedPositionals():
    def func1(): pass
    def func2(a, b, c): pass
    def func3(a, b, c, d=None, e=None): pass
    def func4(*args): pass
    def func5(*args, **kwargs): pass
    def func6(a, b, *args): pass
    def func7(a, b, *args, **kwargs): pass

    tests = [
        (func1, [],        []),
        (func2, [1, 2, 3], ['a', 'b', 'c']),
        (func3, [1, 2, 3], ['a', 'b', 'c']),
        (func4, [1, 2, 3], ['args0', 'args1', 'args2']),
        (func5, [1, 2, 3], ['args0', 'args1', 'args2']),
        (func6, [1, 2, 3], ['a', 'b', 'args0']),
        (func7, [1, 2, 3], ['a', 'b', 'args0']),
    ]

    for func, args, expected in tests:
        result = wutils.namedPositionals(func, args)
        assert list(result) == list(expected)
175

176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233

def test_fileOrArray():

    @wutils.fileOrArray('arr1', 'other', 'output')
    def func(arr1, **kwargs):
        arr1  = np.loadtxt(arr1)
        other = np.loadtxt(kwargs['other'])
        np.savetxt(kwargs['output'], (arr1 * other))

    with tempdir.tempdir():

        arr1     = np.array([[1,  2], [ 3,  4]])
        other    = np.array([[5,  6], [ 7,  8]])
        expected = np.array([[5, 12], [21, 32]])
        np.savetxt('arr1.txt',  arr1)
        np.savetxt('other.txt', other)

        # file  file  file
        func('arr1.txt', other='other.txt', output='output.txt')
        assert np.all(np.loadtxt('output.txt') == expected)
        os.remove('output.txt')

        # file  file  array
        result = func('arr1.txt', other='other.txt', output=wutils.LOAD)['output']
        assert np.all(result == expected)

        # file  array file
        func('arr1.txt', other=other, output='output.txt')
        assert np.all(np.loadtxt('output.txt') == expected)
        os.remove('output.txt')

        # file  array array
        result = func('arr1.txt', other=other, output=wutils.LOAD)['output']
        assert np.all(result == expected)

        # array file  file
        func(arr1, other='other.txt', output='output.txt')
        assert np.all(np.loadtxt('output.txt') == expected)
        os.remove('output.txt')

        # array file  array
        result = func(arr1, other='other.txt', output=wutils.LOAD)['output']
        assert np.all(result == expected)

        # array array file
        func(arr1, other=other, output='output.txt')
        assert np.all(np.loadtxt('output.txt') == expected)
        os.remove('output.txt')

        # array array array
        result = func(arr1, other=other, output=wutils.LOAD)['output']
        assert np.all(result == expected)


def test_fileOrImage():

    @wutils.fileOrImage('img1', 'img2', 'output')
    def func(img1, **kwargs):
Paul McCarthy's avatar
Paul McCarthy committed
234
        img1   = np.asanyarray(nib.load(img1).dataobj)
Paul McCarthy's avatar
Paul McCarthy committed
235
        img2   = np.asanyarray(nib.load(kwargs['img2']).dataobj)
236
237
238
239
240
241
242
        output = nib.nifti1.Nifti1Image(img1 * img2, np.eye(4))
        nib.save(output, kwargs['output'])

    with tempdir.tempdir():

        img1     = nib.nifti1.Nifti1Image(np.array([[1,  2], [ 3,  4]]), np.eye(4))
        img2     = nib.nifti1.Nifti1Image(np.array([[5,  6], [ 7,  8]]), np.eye(4))
243
        img3     = nib.nifti1.Nifti1Image(np.array([[1,  2], [ 3,  4]]), np.eye(4))
244
245
246
247
248
249
        expected = np.array([[5, 12], [21, 32]])
        nib.save(img1, 'img1.nii')
        nib.save(img2, 'img2.nii')

        # file  file  file
        func('img1.nii', img2='img2.nii', output='output.nii')
Paul McCarthy's avatar
Paul McCarthy committed
250
        assert np.all(np.asanyarray(nib.load('output.nii').dataobj) == expected)
251
252
253
254
        os.remove('output.nii')

        # file  file  array
        result = func('img1.nii', img2='img2.nii', output=wutils.LOAD)['output']
Paul McCarthy's avatar
Paul McCarthy committed
255
        assert np.all(np.asanyarray(result.dataobj) == expected)
256
257
258

        # file  array file
        func('img1.nii', img2=img2, output='output.nii')
Paul McCarthy's avatar
Paul McCarthy committed
259
        assert np.all(np.asanyarray(nib.load('output.nii').dataobj) == expected)
260
261
262
263
        os.remove('output.nii')

        # file  array array
        result = func('img1.nii', img2=img2, output=wutils.LOAD)['output']
Paul McCarthy's avatar
Paul McCarthy committed
264
        assert np.all(np.asanyarray(result.dataobj) == expected)
265
266
267

        # array file  file
        func(img1, img2='img2.nii', output='output.nii')
Paul McCarthy's avatar
Paul McCarthy committed
268
        assert np.all(np.asanyarray(nib.load('output.nii').dataobj) == expected)
269
270
271
272
        os.remove('output.nii')

        # array file  array
        result = func(img1, img2='img2.nii', output=wutils.LOAD)['output']
Paul McCarthy's avatar
Paul McCarthy committed
273
        assert np.all(np.asanyarray(result.dataobj) == expected)
274
275
276

        # array array file
        func(img1, img2=img2, output='output.nii')
Paul McCarthy's avatar
Paul McCarthy committed
277
        assert np.all(np.asanyarray(nib.load('output.nii').dataobj) == expected)
278
279
280
281
        os.remove('output.nii')

        # array array array
        result = func(img1, img2=img2, output=wutils.LOAD)['output']
Paul McCarthy's avatar
Paul McCarthy committed
282
        assert np.all(np.asanyarray(result.dataobj) == expected)
283

284
285
        # in-memory image, file, file
        result = func(img3, img2='img2.nii', output='output.nii')
Paul McCarthy's avatar
Paul McCarthy committed
286
        assert np.all(np.asanyarray(nib.load('output.nii').dataobj) == expected)
287
288
        os.remove('output.nii')

289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
        # fslimage, file, load
        result = func(fslimage.Image(img1), img2='img2.nii',
                      output=wutils.LOAD)['output']
        assert isinstance(result, fslimage.Image)
        assert np.all(result[:].squeeze() == expected)

        # fslimage, fslimage, load
        result = func(fslimage.Image(img1), img2=fslimage.Image(img2),
                      output=wutils.LOAD)['output']
        assert isinstance(result, fslimage.Image)
        assert np.all(result[:].squeeze() == expected)

        # fslimage, nib.image, load
        result = func(fslimage.Image(img1), img2=img2,
                      output=wutils.LOAD)['output']
        assert isinstance(result, fslimage.Image)
        assert np.all(result[:].squeeze() == expected)

        # nib.image, nib.image, load
        result = func(img1, img2=img2, output=wutils.LOAD)['output']
        assert isinstance(result, nib.nifti1.Nifti1Image)
Paul McCarthy's avatar
Paul McCarthy committed
310
        assert np.all(np.asanyarray(result.dataobj)[:] == expected)
311

312

313
314
315
316
317
def test_fileOrThing_sequence():

    @wutils.fileOrArray('arrs', 'out')
    def func(arrs, out):

318
        if isinstance(arrs, str):
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
            arrs = [arrs]

        arrs = [np.loadtxt(a) for a in arrs]
        res  = np.sum(arrs, axis=0)

        np.savetxt(out, res)

    inputs  = [np.random.randint(1, 10, (3, 3)) for i in range(4)]
    infiles = ['input{}.txt'.format(i) for i in range(len(inputs))]
    exp     = np.sum(inputs, axis=0)

    with tempdir.tempdir():

        for ifile, idata in zip(infiles, inputs):
            np.savetxt(ifile, idata)

        func(inputs, 'result.txt')
        assert np.all(np.loadtxt('result.txt') == exp)

        assert np.all(func(inputs, wutils.LOAD)['out'] == exp)

        func(inputs[0], 'result.txt')
        assert np.all(np.loadtxt('result.txt') == inputs[0])

        assert np.all(func(inputs[0], wutils.LOAD)['out'] == inputs[0])

        func(infiles, 'result.txt')
        assert np.all(np.loadtxt('result.txt') == exp)

        assert np.all(func(infiles, wutils.LOAD)['out'] == exp)

        func(infiles[0], 'result.txt')
        assert np.all(np.loadtxt('result.txt') == inputs[0])

        assert np.all(func(infiles[0], wutils.LOAD)['out'] == inputs[0])


356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
def test_fileOrText():

    @wutils.fileOrText('input', 'output')
    def func(input, output):
        data = open(input).read()
        data = ''.join(['{}{}'.format(c, c) for c in data])
        open(output, 'wt').write(data)

    with tempdir.tempdir():

        data = 'abcdefg'
        exp  = 'aabbccddeeffgg'

        open('input.txt', 'wt').write(data)

        func(pathlib.Path('input.txt'), pathlib.Path('output.txt'))
        assert open('output.txt').read() == exp

        func('abcdefg', pathlib.Path('output.txt'))
        assert open('output.txt').read() == exp

        assert func('12345', wutils.LOAD).output == '1122334455'


380
def test_fileOrThing_outprefix():
381
382
383

    @wutils.fileOrImage('img', outprefix='output_base')
    def basefunc(img, output_base):
Paul McCarthy's avatar
Paul McCarthy committed
384
        img = np.asanyarray(nib.load(img).dataobj)
385
386
387
388
389
390
391

        out1 = nib.nifti1.Nifti1Image(img * 5,  np.eye(4))
        out2 = nib.nifti1.Nifti1Image(img * 10, np.eye(4))

        nib.save(out1, '{}_times5.nii.gz' .format(output_base))
        nib.save(out2, '{}_times10.nii.gz'.format(output_base))

392

393
394
    with tempdir.tempdir() as td:
        img  = nib.nifti1.Nifti1Image(np.array([[1, 2], [3, 4]]), np.eye(4))
Paul McCarthy's avatar
Paul McCarthy committed
395
396
        exp1 = np.asanyarray(img.dataobj) * 5
        exp2 = np.asanyarray(img.dataobj) * 10
397
398
399
        nib.save(img, 'img.nii')

        basefunc('img.nii', 'myout')
Paul McCarthy's avatar
Paul McCarthy committed
400
401
        assert np.all(np.asanyarray(nib.load('myout_times5.nii.gz') .dataobj) == exp1)
        assert np.all(np.asanyarray(nib.load('myout_times10.nii.gz').dataobj) == exp2)
402
403
404
        cleardir(td, 'myout*')

        basefunc(img, 'myout')
Paul McCarthy's avatar
Paul McCarthy committed
405
406
        assert np.all(np.asanyarray(nib.load('myout_times5.nii.gz') .dataobj) == exp1)
        assert np.all(np.asanyarray(nib.load('myout_times10.nii.gz').dataobj) == exp2)
407
408
409
        cleardir(td, 'myout*')

        res = basefunc(img, 'myout', myout_times5=wutils.LOAD)
Paul McCarthy's avatar
Paul McCarthy committed
410
        assert np.all(np.asanyarray(res['myout_times5'].dataobj) == exp1)
411
412
413
        cleardir(td, 'myout*')

        res = basefunc(img, 'myout', myout_times10=wutils.LOAD)
Paul McCarthy's avatar
Paul McCarthy committed
414
        assert np.all(np.asanyarray(res['myout_times10'].dataobj) == exp2)
415
416
417
        cleardir(td, 'myout*')

        res = basefunc(img, 'myout', myout=wutils.LOAD)
Paul McCarthy's avatar
Paul McCarthy committed
418
419
        assert np.all(np.asanyarray(res['myout_times5'] .dataobj) == exp1)
        assert np.all(np.asanyarray(res['myout_times10'].dataobj) == exp2)
420
421
422
        cleardir(td, 'myout*')


423
def test_fileOrThing_outprefix_differentTypes():
424
425
426
427
428

    @wutils.fileOrImage('img', outprefix='outpref')
    def func(img, outpref):

        img  = nib.load(img)
Paul McCarthy's avatar
Paul McCarthy committed
429
        img  = nib.nifti1.Nifti1Image(np.asanyarray(img.dataobj) * 2, np.eye(4))
430
431
432
433
434
435
436
437
438
        text = '1234567890'

        nib.save(img, '{}_image.nii.gz' .format(outpref))

        with open('{}_text.txt'.format(outpref), 'wt') as f:
            f.write(text)

    with tempdir.tempdir() as td:
        img  = nib.nifti1.Nifti1Image(np.array([[1, 2], [3, 4]]), np.eye(4))
Paul McCarthy's avatar
Paul McCarthy committed
439
        expi = np.asanyarray(img.dataobj) * 2
440
441
442
        expt = '1234567890'

        func(img, 'myout')
Paul McCarthy's avatar
Paul McCarthy committed
443
        assert np.all(np.asanyarray(nib.load('myout_image.nii.gz') .dataobj) == expi)
444
445
446
447
448
449
        with open('myout_text.txt', 'rt') as f:
            assert f.read().strip() == expt
        cleardir(td, 'myout*')

        res = func(img, 'myout', myout_image=wutils.LOAD)
        assert list(res.keys()) == ['myout_image']
Paul McCarthy's avatar
Paul McCarthy committed
450
        assert np.all(np.asanyarray(res['myout_image'].dataobj) == expi)
451
452
453
454
        cleardir(td, 'myout*')

        res = func(img, 'myout', myout=wutils.LOAD)
        assert list(res.keys()) == ['myout_image']
Paul McCarthy's avatar
Paul McCarthy committed
455
        assert np.all(np.asanyarray(res['myout_image'].dataobj) == expi)
456
457
458
459
460
461
462
        cleardir(td, 'myout*')

        res = func(img, 'myout', myout_text=wutils.LOAD)
        assert list(res.keys()) == []
        cleardir(td, 'myout*')


463
def test_fileOrThing_outprefix_directory():
464
465
466
467
468
469
470
471

    import logging
    logging.basicConfig()
    logging.getLogger('fsl.wrappers').setLevel(logging.DEBUG)

    @wutils.fileOrImage('img', outprefix='outpref')
    def func(img, outpref):
        img  = nib.load(img)
Paul McCarthy's avatar
Paul McCarthy committed
472
473
        img2 = nib.nifti1.Nifti1Image(np.asanyarray(img.dataobj) * 2, np.eye(4))
        img4 = nib.nifti1.Nifti1Image(np.asanyarray(img.dataobj) * 4, np.eye(4))
474

475
        outdir = op.abspath('{}_imgs'.format(outpref))
476

477
        os.mkdir(outdir)
478

479
480
        nib.save(img2, op.join(outdir, 'img2.nii.gz'))
        nib.save(img4, op.join(outdir, 'img4.nii.gz'))
481

482
483
    with tempdir.tempdir() as td:
        img  = nib.nifti1.Nifti1Image(np.array([[1, 2], [3, 4]]), np.eye(4))
Paul McCarthy's avatar
Paul McCarthy committed
484
485
        exp2 = np.asanyarray(img.dataobj) * 2
        exp4 = np.asanyarray(img.dataobj) * 4
486
487
488
489
490
491
492

        res = func(img, 'myout')
        assert len(res) == 0
        checkdir(td,
                 op.join('myout_imgs', 'img2.nii.gz'),
                 op.join('myout_imgs', 'img4.nii.gz'))
        cleardir(td, 'myout*')
493

494
495
        res = func(img, 'myout', myout_imgs=wutils.LOAD)
        assert len(res) == 2
Paul McCarthy's avatar
Paul McCarthy committed
496
497
        assert np.all(np.asanyarray(res[op.join('myout_imgs', 'img2')].dataobj) == exp2)
        assert np.all(np.asanyarray(res[op.join('myout_imgs', 'img4')].dataobj) == exp4)
498

Paul McCarthy's avatar
Paul McCarthy committed
499
        res = func(img, 'myout', **{op.join('myout_imgs', 'img2') : wutils.LOAD})
500
        assert len(res) == 1
Paul McCarthy's avatar
Paul McCarthy committed
501
        assert np.all(np.asanyarray(res[op.join('myout_imgs', 'img2')].dataobj) == exp2)
502

Paul McCarthy's avatar
Paul McCarthy committed
503
        res = func(img, 'myout', **{op.join('myout_imgs', 'img') : wutils.LOAD})
504
        assert len(res) == 2
Paul McCarthy's avatar
Paul McCarthy committed
505
506
        assert np.all(np.asanyarray(res[op.join('myout_imgs', 'img2')].dataobj) == exp2)
        assert np.all(np.asanyarray(res[op.join('myout_imgs', 'img4')].dataobj) == exp4)
507
508

        os.mkdir('foo')
Paul McCarthy's avatar
Paul McCarthy committed
509
        res = func(img, op.join('foo', 'myout'))
510
511
512
513
514
515
516
        assert len(res) == 0
        checkdir(td,
                 op.join('foo', 'myout_imgs', 'img2.nii.gz'),
                 op.join('foo', 'myout_imgs', 'img4.nii.gz'))
        cleardir(td, 'foo')

        os.mkdir('foo')
Paul McCarthy's avatar
Paul McCarthy committed
517
        res = func(img, op.join('foo', 'myout'), **{op.join('foo', 'myout') : wutils.LOAD})
518
        assert len(res) == 2
Paul McCarthy's avatar
Paul McCarthy committed
519
520
        assert np.all(np.asanyarray(res[op.join('foo', 'myout_imgs', 'img2')].dataobj) == exp2)
        assert np.all(np.asanyarray(res[op.join('foo', 'myout_imgs', 'img4')].dataobj) == exp4)
521

522

523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587

def test_fileOrThing_results():
    @wutils.fileOrArray('input', 'regular_output', outprefix='outpref')
    def func(input, regular_output, outpref):

        input = np.loadtxt(input)

        regout   = input * 2
        prefouts = []
        for i in range(3, 6):
            prefouts.append(input * i)

        np.savetxt(regular_output, regout)
        for i, o in enumerate(prefouts):
            np.savetxt('{}_{}.txt'.format(outpref, i), o)

        return ('return', 'value')

    input  = np.random.randint(1, 10, (3, 3))
    infile = 'input.txt'
    exp    = [input * i for i in range(2, 6)]

    with tempdir.tempdir():

        np.savetxt(infile, input)

        result = func('input.txt', 'regout.txt', 'outpref')
        assert len(result) == 0
        assert result.stdout == ('return', 'value')
        assert (np.loadtxt('regout.txt') == exp[0]).all()
        for i in range(3):
            assert (np.loadtxt('outpref_{}.txt'.format(i)) == exp[i+1]).all()

        result = func(input, 'regout.txt', 'outpref')
        assert len(result) == 0
        assert result.stdout == ('return', 'value')
        assert (np.loadtxt('regout.txt') == exp[0]).all()
        for i in range(3):
            assert (np.loadtxt('outpref_{}.txt'.format(i)) == exp[i+1]).all()

        result = func(input, wutils.LOAD, 'outpref')
        assert len(result) == 1
        assert result.stdout == ('return', 'value')
        assert (result .regular_output == exp[0]).all()
        assert (result['regular_output'] == exp[0]).all()
        for i in range(3):
            assert (np.loadtxt('outpref_{}.txt'.format(i)) == exp[i+1]).all()

        # todo outpref
        result = func(input, wutils.LOAD, wutils.LOAD)
        assert len(result) == 4
        assert result.stdout == ('return', 'value')
        assert (result .regular_output == exp[0]).all()
        assert (result['regular_output'] == exp[0]).all()

        assert (result .outpref_0   == exp[1]).all()
        assert (result['outpref_0'] == exp[1]).all()
        assert (result .outpref_1   == exp[2]).all()
        assert (result['outpref_1'] == exp[2]).all()
        assert (result .outpref_2   == exp[3]).all()
        assert (result['outpref_2'] == exp[3]).all()

        for i in range(3):
            assert (np.loadtxt('outpref_{}.txt'.format(i)) == exp[i+1]).all()

Paul McCarthy's avatar
Paul McCarthy committed
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
        result = func(input, wutils.LOAD, wutils.LOAD)
        assert len(result) == 4


def test_FileOrThing_invalid_identifiers():
    # unlikely to ever happen, but let's test arguments with
    # names that are not valid python identifiers
    @wutils.fileOrArray('in val', '2out')
    def func(**kwargs):

        infile  = kwargs['in val']
        outfile = kwargs['2out']

        input = np.loadtxt(infile)
        np.savetxt(outfile, input * 2)

        return ('return', 'value')

    input  = np.random.randint(1, 10, (3, 3))
    infile = 'input.txt'
    exp    = input * 2

    with tempdir.tempdir():

        np.savetxt(infile, input)

        res = func(**{'in val' : infile, '2out' : 'output.txt'})
        assert res.stdout == ('return', 'value')
        assert (np.loadtxt('output.txt') == exp).all()

        res = func(**{'in val' : input, '2out' : 'output.txt'})
        assert res.stdout == ('return', 'value')
        assert (np.loadtxt('output.txt') == exp).all()

        res = func(**{'in val' : input, '2out' : wutils.LOAD})
        assert res.stdout == ('return', 'value')
        assert (res['2out'] == exp).all()

626
627


628
def test_chained_fileOrImageAndArray():
629
630
631
632
633
634
    @wutils.fileOrImage('image', 'outimage')
    @wutils.fileOrArray('array', 'outarray')
    def func(image, array, outimage, outarray):
        image = nib.load(image)
        array = np.loadtxt(array)

Paul McCarthy's avatar
Paul McCarthy committed
635
        outimg = nib.nifti1.Nifti1Image(np.asanyarray(image.dataobj) * 2, np.eye(4))
636
637
638

        np.savetxt(outarray, array * 2)
        outimg.to_filename(outimage)
639
640
641
642

    image = nib.nifti1.Nifti1Image(np.array([[1,  2], [ 3,  4]]), np.eye(4))
    array = np.array([[5, 6, 7, 8]])

Paul McCarthy's avatar
Paul McCarthy committed
643
    expimg = nib.nifti1.Nifti1Image(np.asanyarray(image.dataobj) * 2, np.eye(4))
644
645
    exparr = array * 2

646
647
648
649
650
    with tempdir.tempdir():

        nib.save(image, 'image.nii')
        np.savetxt('array.txt', array)

651
        func('image.nii', 'array.txt', 'outimg.nii', 'outarr.txt')
Paul McCarthy's avatar
Paul McCarthy committed
652
        assert np.all(np.asanyarray(nib.load('outimg.nii').dataobj) == np.asanyarray(expimg.dataobj))
653
654
655
        assert np.all(np.loadtxt('outarr.txt') == exparr)

        func('image.nii', array, 'outimg.nii', 'outarr.txt')
Paul McCarthy's avatar
Paul McCarthy committed
656
        assert np.all(np.asanyarray(nib.load('outimg.nii').dataobj) == np.asanyarray(expimg.dataobj))
657
658
659
        assert np.all(np.loadtxt('outarr.txt') == exparr)

        func( image, 'array.txt', 'outimg.nii', 'outarr.txt')
Paul McCarthy's avatar
Paul McCarthy committed
660
        assert np.all(np.asanyarray(nib.load('outimg.nii').dataobj) == np.asanyarray(expimg.dataobj))
661
662
663
        assert np.all(np.loadtxt('outarr.txt') == exparr)

        func( image, array, 'outimg.nii', 'outarr.txt')
Paul McCarthy's avatar
Paul McCarthy committed
664
        assert np.all(np.asanyarray(nib.load('outimg.nii').dataobj) == np.asanyarray(expimg.dataobj))
665
666
667
        assert np.all(np.loadtxt('outarr.txt') == exparr)

        res = func(image, array, wutils.LOAD, 'outarr.txt')
Paul McCarthy's avatar
Paul McCarthy committed
668
        assert np.all(np.asanyarray(res['outimage'].dataobj) == np.asanyarray(expimg.dataobj))
669
670
671
        assert np.all(np.loadtxt('outarr.txt') == exparr)

        res = func(image, array, 'outimg.nii', wutils.LOAD)
Paul McCarthy's avatar
Paul McCarthy committed
672
        assert np.all(np.asanyarray(nib.load('outimg.nii').dataobj) == np.asanyarray(expimg.dataobj))
673
674
675
        assert np.all(res['outarray'] == exparr)

        res = func(image, array, wutils.LOAD, wutils.LOAD)
Paul McCarthy's avatar
Paul McCarthy committed
676
        assert np.all(np.asanyarray(res['outimage'].dataobj) == np.asanyarray(expimg.dataobj))
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
        assert np.all(res['outarray'] == exparr)


def test_fileOrThing_chained_outprefix():

    import logging
    logging.basicConfig()
    logging.getLogger('fsl.wrappers').setLevel(logging.DEBUG)

    @wutils.fileOrImage('image', 'outimage', outprefix='out')
    @wutils.fileOrArray('array', 'outarray', outprefix='out')
    def func(image, array, out, **kwa):

        image = nib.load(image)
        array = np.loadtxt(array)

Paul McCarthy's avatar
Paul McCarthy committed
693
        outimg = nib.nifti1.Nifti1Image(np.asanyarray(image.dataobj) * 2, np.eye(4))
694
695
696
697
698
699
700
701
        outarr = array * 2

        np.savetxt('{}_array.txt'.format(out), outarr)
        outimg.to_filename('{}_image.nii'.format(out))

    image = nib.nifti1.Nifti1Image(np.array([[1,  2], [ 3,  4]]), np.eye(4))
    array = np.array([[5, 6, 7, 8]])

Paul McCarthy's avatar
Paul McCarthy committed
702
    expimg = nib.nifti1.Nifti1Image(np.asanyarray(image.dataobj) * 2, np.eye(4))
703
704
705
706
707
    exparr = array * 2

    with tempdir.tempdir():

        func(image, array, 'myout')
Paul McCarthy's avatar
Paul McCarthy committed
708
        assert np.all(np.asanyarray(nib.load('myout_image.nii').dataobj) == np.asanyarray(expimg.dataobj))
709
710
711
        assert np.all(np.loadtxt('myout_array.txt') == exparr)

        res = func(image, array, wutils.LOAD)
Paul McCarthy's avatar
Paul McCarthy committed
712
        assert np.all(np.asanyarray(res['out_image'].dataobj) == np.asanyarray(expimg.dataobj))
713
        assert np.all(res['out_array'] == exparr)
714
715


716
def test_fileOrThing_submit_cmdonly():
717
718

    @wutils.fileOrImage('input', 'output')
719
    def func(input, output, submit=False, cmdonly=False):
720
721
722

        if submit:
            return 'submitted!'
723
724
        if cmdonly:
            return 'cmdonly!'
725
726
727
728
729
730
731
732
733
734
735
736
737
738

        img = nib.load(input)
        img = nib.nifti1.Nifti1Image(np.asanyarray(img.dataobj) * 2, np.eye(4))

        nib.save(img, output)

    with tempdir.tempdir() as td:
        img = nib.nifti1.Nifti1Image(np.array([[1, 2], [3, 4]]), np.eye(4))
        exp = np.asanyarray(img.dataobj) * 2
        nib.save(img, 'input.nii.gz')

        result = func(img, wutils.LOAD)
        assert np.all(np.asanyarray(result['output'].dataobj) == exp)

739
740
        assert func('input.nii.gz', 'output.nii.gz', submit=True)  == 'submitted!'
        assert func('input.nii.gz', 'output.nii.gz', cmdonly=True) == 'cmdonly!'
741
742
743
744
745
746
747
748
749

        with pytest.raises(ValueError):
            func(img, wutils.LOAD, submit=True)
        with pytest.raises(ValueError):
            func(img, 'output.nii.gz', submit=True)
        with pytest.raises(ValueError):
            func('input.nii.gz', wutils.LOAD, submit=True)


750
751
752
753
754
755
756
757
def test_cmdwrapper():
    @wutils.cmdwrapper
    def func(a, b):
        return ['func', str(a), str(b)]

    with run.dryrun():
        assert func(1, 2)[0] == 'func 1 2'

Paul McCarthy's avatar
Paul McCarthy committed
758
759
    assert func(1, 2, cmdonly=True) == ['func', '1', '2']

760
761
762
763
764
765

def test_fslwrapper():
    @wutils.fslwrapper
    def func(a, b):
        return ['func', str(a), str(b)]

Paul McCarthy's avatar
Paul McCarthy committed
766
    with mockFSLDIR(bin=('func',)) as fsldir:
767
        expected = '{} 1 2'.format(op.join(fsldir, 'bin', 'func'))
Paul McCarthy's avatar
Paul McCarthy committed
768
769
770
        with run.dryrun():
            assert func(1, 2)[0] == expected

771
        assert func(1, 2, cmdonly=True) == list(shlex.split(expected))
772
773
774
775
776
777
778
779
780
781
782
783
784


_test_script = textwrap.dedent("""
#!/usr/bin/env bash
echo "test_script running: $1 $2"
exit 0
""").strip()


def _test_script_func(a, b):
    return ['test_script', str(a), str(b)]


Paul McCarthy's avatar
Paul McCarthy committed
785
@pytest.mark.unixtest
786
787
788
789
790
791
def test_cmdwrapper_submit():

    test_func = wutils.cmdwrapper(_test_script_func)
    newpath = op.pathsep.join(('.', os.environ['PATH']))

    with tempdir.tempdir(), \
792
         mock.patch('fsl.wrappers.fsl_sub', mock_fsl_sub), \
793
794
795
796
797
798
799
800
         mock.patch.dict(os.environ, {'PATH' : newpath}):

        with open('test_script', 'wt') as f:
            f.write(_test_script)
        os.chmod('test_script', 0o755)

        jid = test_func(1, 2, submit=True)

801
        assert jid == '12345'
802
803
804
805
806
807
808

        stdout, stderr = fslsub.output('12345')

        assert stdout.strip() == 'test_script running: 1 2'
        assert stderr.strip() == ''


Paul McCarthy's avatar
Paul McCarthy committed
809
@pytest.mark.unixtest
810
811
812
813
814
def test_fslwrapper_submit():

    test_func = wutils.fslwrapper(_test_script_func)

    with mockFSLDIR() as fsldir, \
815
         mock.patch('fsl.wrappers.fsl_sub', mock_fsl_sub):
816
817
818
819
820
821
822
823
824

        test_file = op.join(fsldir, 'bin', 'test_script')

        with open(test_file, 'wt') as f:
            f.write(_test_script)
        os.chmod(test_file, 0o755)

        jid = test_func(1, 2, submit=True)

Paul McCarthy's avatar
Paul McCarthy committed
825
        assert jid == '12345'
826
827
828
829
830
831
832
833
834
835

        stdout, stderr = fslsub.output('12345')

        assert stdout.strip() == 'test_script running: 1 2'
        assert stderr.strip() == ''

        kwargs = {'name' : 'abcde', 'ram' : '4GB'}

        jid = test_func(1, 2, submit=kwargs)

Paul McCarthy's avatar
Paul McCarthy committed
836
        assert jid == '12345'
837
838
839

        stdout, stderr = fslsub.output('12345')

Paul McCarthy's avatar
Paul McCarthy committed
840
841
        experr = '\n'.join(['{}: {}'.format(k, kwargs[k])
                            for k in sorted(kwargs.keys())])
842
843
844

        assert stdout.strip() == 'test_script running: 1 2'
        assert stderr.strip() == experr
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862


@pytest.mark.unixtest
def test_cmdwrapper_fileorthing_cmdonly():

    test_func = wutils.fileOrImage('a')(wutils.cmdwrapper(_test_script_func))
    newpath   = op.pathsep.join(('.', os.environ['PATH']))
    with tempdir.tempdir(), \
         mock.patch.dict(os.environ, {'PATH' : newpath}):

        with open('test_script', 'wt') as f:
            f.write(_test_script)
        os.chmod('test_script', 0o755)

        ran = test_func('1', '2')
        cmd = test_func('1', '2', cmdonly=True)
        assert ran.stdout[0].strip() == 'test_script running: 1 2'
        assert cmd                   == ['test_script', '1', '2']
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878


def test_cmdwrapper_cmdonly_assert():

    @wutils.cmdwrapper
    def func():
        asrt.assertFileExists('file')
        return ['echo', 'hello']

    with tempdir.tempdir():
        with pytest.raises(AssertionError):
            func()
        touch('file')
        assert func()[0].strip() == 'hello'
        os.remove('file')
        assert func(cmdonly=True) == ['echo', 'hello']