test_run.py 11.8 KB
Newer Older
Paul McCarthy's avatar
Paul McCarthy committed
1
2
3
4
5
6
7
8
9
10
#!/usr/bin/env python
#
# test_run.py -
#
# Author: Paul McCarthy <pauldmccarthy@gmail.com>
#


import os.path as op
import            os
11
import            shutil
Paul McCarthy's avatar
Paul McCarthy committed
12
13
14
15
16
17
18
import            textwrap

# python 3
try:  from unittest import mock
# python 2
except ImportError: import mock

19
import six
Paul McCarthy's avatar
Paul McCarthy committed
20
21
22
23
24
import pytest

import fsl.utils.tempdir                  as tempdir
from   fsl.utils.platform import platform as fslplatform
import fsl.utils.run                      as run
25
import fsl.utils.fslsub                   as fslsub
Paul McCarthy's avatar
Paul McCarthy committed
26

Paul McCarthy's avatar
Paul McCarthy committed
27
from . import make_random_image, mockFSLDIR, CaptureStdout
Paul McCarthy's avatar
Paul McCarthy committed
28
29


Paul McCarthy's avatar
Paul McCarthy committed
30
31
32
pytestmark = pytest.mark.unixtest


33
34
35
36
37
38
def mkexec(path, contents):
    with open(path, 'wt') as f:
        f.write(contents)
    os.chmod(path, 0o755)


39
40
41
42
43
44
45
46
47
48
49
def test_prepareArgs():
    tests = [
        ('a b c',              ['a', 'b', 'c']),
        (['a', 'b', 'c'],      ['a', 'b', 'c']),
        ('abc "woop woop"',    ['abc', 'woop woop']),
        (['abc', 'woop woop'], ['abc', 'woop woop']),
    ]

    for args, expected in tests:
        assert run.prepareArgs((args, )) == expected

Paul McCarthy's avatar
Paul McCarthy committed
50
51
52
53
54
55
56
57
58
59
60
61
62
def test_run():

    test_script = textwrap.dedent("""
    #!/bin/bash

    echo "standard output - arguments: $@"
    echo "standard error" >&2
    exit {}
    """).strip()

    with tempdir.tempdir():

        # return code == 0
63
        mkexec('script.sh', test_script.format(0))
Paul McCarthy's avatar
Paul McCarthy committed
64

Paul McCarthy's avatar
Paul McCarthy committed
65
66
        expstdout = "standard output - arguments: 1 2 3\n"
        expstderr = "standard error\n"
Paul McCarthy's avatar
Paul McCarthy committed
67
68
69
70
71

        # test:
        #   - single string
        #   - packed sequence
        #   - unpacked sequence
Paul McCarthy's avatar
Paul McCarthy committed
72
73
        assert run.run('./script.sh 1 2 3')             == expstdout
        assert run.run(('./script.sh', '1', '2', '3'))  == expstdout
Paul McCarthy's avatar
Paul McCarthy committed
74
75
76
        assert run.run(*('./script.sh', '1', '2', '3')) == expstdout

        # test stdout/stderr
77
        stdout, stderr = run.run('./script.sh 1 2 3', stderr=True)
Paul McCarthy's avatar
Paul McCarthy committed
78
79
        assert stdout == expstdout
        assert stderr == expstderr
Paul McCarthy's avatar
Paul McCarthy committed
80
81

        # test return code
82
        res = run.run('./script.sh 1 2 3', exitcode=True)
83
        stdout, ret = res
Paul McCarthy's avatar
Paul McCarthy committed
84
        assert stdout == expstdout
Paul McCarthy's avatar
Paul McCarthy committed
85
        assert ret == 0
86
87
        stdout, stderr, ret = run.run('./script.sh 1 2 3', stderr=True,
                                      exitcode=True)
Paul McCarthy's avatar
Paul McCarthy committed
88
89
        assert stdout == expstdout
        assert stderr == expstderr
Paul McCarthy's avatar
Paul McCarthy committed
90
91
        assert ret == 0

92
93
94
95
96
97
        # stdout=False
        res = run.run('./script.sh 1 2 3', stdout=False)
        assert res == ()
        stderr = run.run('./script.sh 1 2 3', stdout=False, stderr=True)
        assert stderr == expstderr

Paul McCarthy's avatar
Paul McCarthy committed
98
        # return code != 0
99
        mkexec('./script.sh', test_script.format(255))
Paul McCarthy's avatar
Paul McCarthy committed
100
101
102
103

        with pytest.raises(RuntimeError):
            run.run('./script.sh 1 2 3')

104
        stdout, ret = run.run('./script.sh 1 2 3', exitcode=True)
Paul McCarthy's avatar
Paul McCarthy committed
105
        assert stdout == expstdout
Paul McCarthy's avatar
Paul McCarthy committed
106
107
108
        assert ret == 255


Paul McCarthy's avatar
Paul McCarthy committed
109
110
111
112
113
114
115
116
117
118
def test_run_tee():
    test_script = textwrap.dedent("""
    #!/bin/bash

    echo "standard output - arguments: $@"
    echo "standard error" >&2
    exit 0
    """).strip()

    with tempdir.tempdir():
119
        mkexec('script.sh', test_script)
Paul McCarthy's avatar
Paul McCarthy committed
120
121
122
123
124
125
126

        expstdout = "standard output - arguments: 1 2 3\n"
        expstderr = "standard error\n"

        capture = CaptureStdout()

        with capture:
127
            stdout = run.run('./script.sh 1 2 3', log={'tee' : True})
Paul McCarthy's avatar
Paul McCarthy committed
128
129
130
131
132

        assert stdout         == expstdout
        assert capture.stdout == expstdout

        with capture.reset():
133
134
            stdout, stderr = run.run('./script.sh 1 2 3', stderr=True,
                                     log={'tee' : True})
Paul McCarthy's avatar
Paul McCarthy committed
135
136
137
138
139
140
141
142

        assert stdout         == expstdout
        assert stderr         == expstderr
        assert capture.stdout == expstdout
        assert capture.stderr == expstderr

        with capture.reset():
            stdout, stderr, ret = run.run('./script.sh 1 2 3',
143
144
145
                                          stderr=True,
                                          exitcode=True,
                                          log={'tee' : True})
Paul McCarthy's avatar
Paul McCarthy committed
146
147
148
149
150
151
152
153

        assert ret            == 0
        assert stdout         == expstdout
        assert stderr         == expstderr
        assert capture.stdout == expstdout
        assert capture.stderr == expstderr

        with capture.reset():
154
155
156
            stdout, ret = run.run('./script.sh 1 2 3',
                                  exitcode=True,
                                  log={'tee' : True})
Paul McCarthy's avatar
Paul McCarthy committed
157
158
159
160
161
162

        assert ret            == 0
        assert stdout         == expstdout
        assert capture.stdout == expstdout


163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
def test_run_passthrough():

    test_script = textwrap.dedent("""
    #!/bin/bash

    echo "env: $RUN_TEST_ENV_VAR"
    """).strip()

    with tempdir.tempdir():

        # return code == 0
        mkexec('script.sh', test_script.format(0))

        env       = {'RUN_TEST_ENV_VAR' : 'howdy ho'}
        expstdout = "env: howdy ho\n"

        assert run.run('./script.sh', env=env) == expstdout


Paul McCarthy's avatar
Paul McCarthy committed
182
183
184
185
186
187
188
def test_cmdonly():
    assert run.run('script.sh',        cmdonly=True) == ['script.sh']
    assert run.run('script.sh 1 2 3',  cmdonly=True) == ['script.sh', '1', '2', '3']
    assert run.run(['script.sh'],      cmdonly=True) == ['script.sh']
    assert run.run(['script.sh', '1'], cmdonly=True) == ['script.sh', '1']


Paul McCarthy's avatar
Paul McCarthy committed
189
190
191
192
193
194
195
196
def test_dryrun():

    test_script = textwrap.dedent("""
    #!/bin/bash
    touch foo
    """).strip()

    with tempdir.tempdir():
197
        mkexec('./script.sh', test_script)
Paul McCarthy's avatar
Paul McCarthy committed
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214

        run.run('./script.sh')
        assert op.exists('foo')

        os.remove('foo')

        with run.dryrun():
            run.run('./script.sh')

        assert not op.exists('foo')


# test runfsl with/without $FSLDIR
def test_runfsl():

    test_script = textwrap.dedent("""
    #!/bin/bash
215
    echo {}
Paul McCarthy's avatar
Paul McCarthy committed
216
217
218
    exit 0
    """).strip()

219
220
221
    old_fsldir    = fslplatform.fsldir
    old_fsldevdir = fslplatform.fsldevdir

Paul McCarthy's avatar
Paul McCarthy committed
222
223
224
225
226
227
    try:
        with tempdir.tempdir():

            make_random_image('image.nii.gz')

            # no FSLDIR - should error
228
229
            fslplatform.fsldir    = None
            fslplatform.fsldevdir = None
Paul McCarthy's avatar
Paul McCarthy committed
230
            with pytest.raises(run.FSLNotPresent):
231
                run.runfsl('fslhd')
Paul McCarthy's avatar
Paul McCarthy committed
232
233
234
235
236

            # FSLDIR/bin exists - should be good
            fsldir = op.abspath('./fsl')
            fslhd  = op.join(fsldir, 'bin', 'fslhd')
            os.makedirs(op.join(fsldir, 'bin'))
237
238

            mkexec(fslhd, test_script.format('fsldir'))
Paul McCarthy's avatar
Paul McCarthy committed
239
240

            fslplatform.fsldir = fsldir
241
242
            assert run.runfsl('fslhd').strip() == 'fsldir'

243
244
245
246
            # non-FSL command - should error
            with pytest.raises(FileNotFoundError):
                run.runfsl('ls')

247
248
249
250
            # FSLDEVDIR should take precedence
            fsldevdir = './fsldev'
            fslhd  = op.join(fsldevdir, 'bin', 'fslhd')
            shutil.copytree(fsldir, fsldevdir)
251
252

            mkexec(fslhd, test_script.format('fsldevdir'))
253
254
255
256
257
258
259
260
261

            fslplatform.fsldevdir = fsldevdir
            fslplatform.fsldir    = None
            assert run.runfsl('fslhd').strip() == 'fsldevdir'

            # FSL_PREFIX should override all
            override = './override'
            fslhd    = op.join(override, 'fslhd')
            os.makedirs(override)
262
            mkexec(fslhd, test_script.format('override'))
263
264
265
266
267
268

            fslplatform.fsldir    = None
            fslplatform.fsldevdir = None
            run.FSL_PREFIX = override
            assert run.runfsl('fslhd').strip() == 'override'

Paul McCarthy's avatar
Paul McCarthy committed
269
    finally:
270
271
272
        fslplatform.fsldir    = old_fsldir
        fslplatform.fsldevdir = old_fsldevdir
        run.FSL_PREFIX        = None
273
274


275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
def mock_submit(cmd, **kwargs):
    if isinstance(cmd, six.string_types):
        name = cmd.split()[0]
    else:
        name = cmd[0]

    name = op.basename(name)

    jid = '12345'
    output = run.run(cmd)

    with open('{}.o{}'.format(name, jid), 'wt') as f:
        f.write(output)

    with open('{}.e{}'.format(name, jid), 'wt') as f:
Paul McCarthy's avatar
Paul McCarthy committed
290
291
        for k in sorted(kwargs.keys()):
            f.write('{}: {}\n'.format(k, kwargs[k]))
292

293
    return jid
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308


def test_run_submit():

    def mkexec(path, contents):
        with open(path, 'wt') as f:
            f.write(contents)
        os.chmod(path, 0o755)

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

309
310
311
    with tempdir.tempdir(), \
         mockFSLDIR(), \
         mock.patch('fsl.utils.fslsub.submit', mock_submit):
312
313
314

        mkexec(op.expandvars('$FSLDIR/bin/fsltest'), test_script)

315
        jid = run.run('fsltest', submit=True)
316
        assert jid == '12345'
317
        stdout, stderr = fslsub.output(jid)
Paul McCarthy's avatar
Paul McCarthy committed
318
319
        assert stdout == 'test_script running\n'
        assert stderr == ''
320

Paul McCarthy's avatar
Paul McCarthy committed
321
        # or can pass submit opts as a dict
322
        kwargs = {'name' : 'abcde', 'ram' : '4GB'}
323
        jid = run.run('fsltest', submit=kwargs)
324
325
        assert jid == '12345'
        stdout, stderr = fslsub.output(jid)
Paul McCarthy's avatar
Paul McCarthy committed
326
        experr = '\n'.join(['{}: {}'.format(k, kwargs[k])
Paul McCarthy's avatar
Paul McCarthy committed
327
                            for k in sorted(kwargs.keys())]) + '\n'
Paul McCarthy's avatar
Paul McCarthy committed
328
329
        assert stdout == 'test_script running\n'
        assert stderr == experr
330

Paul McCarthy's avatar
Paul McCarthy committed
331
332
333
334
335
336
337
        # or can pass submit opts as kwargs
        kwargs = {'name' : 'abcde', 'ram' : '4GB'}
        jid = run.run('fsltest', submit=True, **kwargs)
        assert jid == '12345'
        stdout, stderr = fslsub.output(jid)
        experr = '\n'.join(['{}: {}'.format(k, kwargs[k])
                            for k in sorted(kwargs.keys())]) + '\n'
Paul McCarthy's avatar
Paul McCarthy committed
338
339
        assert stdout == 'test_script running\n'
        assert stderr == experr
340
341


Paul McCarthy's avatar
Paul McCarthy committed
342

343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
def test_run_streams():
    """
    """

    test_script = textwrap.dedent("""
    #!/usr/bin/env bash
    echo standard output
    echo standard error >&2
    exit 0
    """).strip()

    expstdout = 'standard output\n'
    expstderr = 'standard error\n'

    with tempdir.tempdir():
        mkexec('./script.sh', test_script)

        with open('my_stdout', 'wt') as stdout, \
             open('my_stderr', 'wt') as stderr:

            stdout, stderr = run.run('./script.sh',
                                     stderr=True,
                                     log={'stdout' : stdout,
                                          'stderr' : stderr})

        assert stdout                         == expstdout
        assert stderr                         == expstderr
        assert open('my_stdout', 'rt').read() == expstdout
        assert open('my_stderr', 'rt').read() == expstderr


        capture = CaptureStdout()

        with open('my_stdout', 'wt') as stdout, \
             open('my_stderr', 'wt') as stderr, \
             capture.reset():

            stdout, stderr = run.run('./script.sh',
                                     stderr=True,
                                     log={'tee'    : True,
                                          'stdout' : stdout,
                                          'stderr' : stderr})

        assert stdout                         == expstdout
        assert stderr                         == expstderr
        assert capture.stdout                 == expstdout
        assert capture.stderr                 == expstderr
        assert open('my_stdout', 'rt').read() == expstdout
        assert open('my_stderr', 'rt').read() == expstderr


def test_run_logcmd():
    test_script = textwrap.dedent("""
    #!/usr/bin/env bash
    echo output $@
    exit 0
    """).strip()

401
402
    expcmd = './script.sh 1 2 3\n'
    expstdout = 'output 1 2 3\n'
403
404
405
406

    with tempdir.tempdir():
        mkexec('script.sh', test_script)

407
408
409
410
411
412
        with open('my_stdout', 'wt') as stdoutf:
            stdout = run.run('./script.sh 1 2 3',
                             log={'cmd' : stdoutf})

        assert stdout                         == expstdout
        assert open('my_stdout', 'rt').read() == expcmd
413
414
415

        with open('my_stdout', 'wt') as stdoutf:
            stdout = run.run('./script.sh 1 2 3',
416
                             log={'cmd' : stdoutf, "stdout" : stdoutf})
417
418

        assert stdout                         == expstdout
419
        assert open('my_stdout', 'rt').read() == expcmd + expstdout