test_fslsub.py 9.46 KB
Newer Older
1
2
3
4
5
#!/usr/bin/env python
#
# test_fslsub.py - Tests functions in the fsl.utils.fslsub module.
#
# Author: Michiel Cottaar <Michiel.Cottaar@ndcn.ox.ac.uk>
Paul McCarthy's avatar
Paul McCarthy committed
6
# Author: Paul McCarthy   <pauldmccarthy@gmail.com>
7
8
#

Paul McCarthy's avatar
Paul McCarthy committed
9
10
11
12
13
14

import os
import os.path as op
import sys
import textwrap as tw
import contextlib
15
import argparse
16
import pytest
Paul McCarthy's avatar
Paul McCarthy committed
17

18
import fsl
19
from fsl.utils         import fslsub, run
Paul McCarthy's avatar
Paul McCarthy committed
20
21
22
23
24
from fsl.utils.tempdir import tempdir

from . import mockFSLDIR


25
mock_fsl_sub = """
26
#!/usr/bin/env python3
Paul McCarthy's avatar
Paul McCarthy committed
27
28
29
30
31
32

import random
import os
import os.path as op
import sys
import subprocess as sp
33
34
35
36
37
38
39

fslpydir = op.join('{}', '..')
env = dict(os.environ)

env['PYTHONPATH'] = fslpydir
sys.path.insert(0, fslpydir)

Paul McCarthy's avatar
Paul McCarthy committed
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import fsl

args = sys.argv[1:]

for i in range(len(args)):
    a = args[i]
    if a[0] == '-':
       if a[1] == 's':
           i += 2
       elif a[1] not in ('F', 'v'):
           i += 1
       continue
    else:
        break

args = args[i:]

cmd   = op.basename(args[0])
jobid = random.randint(1, 9999)

Paul McCarthy's avatar
Paul McCarthy committed
60
61
with open('{{}}.o{{}}'.format(cmd, jobid), 'w') as stdout, \
     open('{{}}.e{{}}'.format(cmd, jobid), 'w') as stderr:
Paul McCarthy's avatar
Paul McCarthy committed
62
63
64
65
    result = sp.run(args, stdout=stdout, stderr=stderr, env=env)

print(str(jobid))
sys.exit(0)
66
""".format(op.dirname(fsl.__file__)).strip()
Paul McCarthy's avatar
Paul McCarthy committed
67
68
69
70
71
72
73
74
75

@contextlib.contextmanager
def fslsub_mockFSLDIR():
    with mockFSLDIR() as fsldir:
        fslsubbin = op.join(fsldir, 'bin', 'fsl_sub')
        with open(fslsubbin, 'wt') as f:
            f.write(mock_fsl_sub)
        os.chmod(fslsubbin, 0o755)
        yield fsldir
76
77
78


def test_flatten_jobids():
79
    job_ids = ('12', '27', '35', '41', 721)
80
81
82
83
84
85
86
87
    res = '12,27,35,41,721'

    assert fslsub._flatten_job_ids(job_ids) == res
    assert fslsub._flatten_job_ids(job_ids[::-1]) == res
    assert fslsub._flatten_job_ids('12') == '12'
    assert fslsub._flatten_job_ids([job_ids[:2], job_ids[2:]]) == res
    assert fslsub._flatten_job_ids([set(job_ids[:2]), job_ids[2:]]) == res
    assert fslsub._flatten_job_ids(((job_ids, ), job_ids + job_ids)) == res
Paul McCarthy's avatar
Paul McCarthy committed
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109


def test_submit():
    script = tw.dedent("""#!/usr/bin/env bash
    echo "standard output"
    echo "standard error" >&2
    exit 0
    """).strip()

    with fslsub_mockFSLDIR(), tempdir():
        cmd = op.join('.', 'myscript')
        with open(cmd, 'wt') as f:
            f.write(script)
        os.chmod(cmd, 0o755)

        jid = fslsub.submit(cmd)
        stdout, stderr = fslsub.output(jid)

        assert stdout.strip() == 'standard output'
        assert stderr.strip() == 'standard error'


Paul McCarthy's avatar
Paul McCarthy committed
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
def test_info():
    mock_qstat = tw.dedent("""
    #!/usr/bin/env bash
    echo "#####################"
    echo "job_number:        1 "
    echo "exec_file:         2 "
    echo "submission_time:   3 "
    echo "owner:             4 "
    """).strip()

    with mockFSLDIR() as fsldir:
        qstatbin = op.join(fsldir, 'bin', 'qstat')
        with open(qstatbin, 'wt') as f:
            f.write(mock_qstat)
        os.chmod(qstatbin, 0o755)

        exp = {'job_number'      : '1',
               'exec_file'       : '2',
               'submission_time' : '3',
               'owner'           : '4'}
        assert fslsub.info('12345') == exp


133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
def test_add_to_parser():
    test_flags = [
        ('-T', '30.0'),
        ('-q', 'short.q'),
        ('-a', 'architecture'),
        ('-p', '3'),
        ('-M', 'test@something.com'),
        ('-N', 'job_name'),
        ('-R', '20'),
        ('-l', 'logdir'),
        ('-j', '12345,67890'),
        ('-m', 'mail_options'),
        ('-v', ),
        ('-F', ),
        ('-s', 'pename,thread')
    ]
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
    with fslsub_mockFSLDIR():
        for flag in test_flags:
            for include in (None, [flag[0]]):
                parser = argparse.ArgumentParser("test parser")
                fslsub.SubmitParams.add_to_parser(parser, include=include)
                args = parser.parse_args(flag)
                submitter = fslsub.SubmitParams.from_args(args)
                assert submitter.as_flags() == flag

    with fslsub_mockFSLDIR():
        parser = argparse.ArgumentParser("test parser")
        parser.add_argument('some_input')
        fslsub.SubmitParams.add_to_parser(parser, include=None)
        all_flags = tuple(part for flag in test_flags for part in flag)
        args = parser.parse_args(('input', ) + all_flags)
        assert args.some_input == 'input'
        submitter = fslsub.SubmitParams.from_args(args)
        assert len(all_flags) == len(submitter.as_flags())

        for flag in test_flags:
            res_flags = submitter.as_flags()
            assert flag[0] in res_flags
            start_index = res_flags.index(flag[0])
            for idx, part in enumerate(flag):
                assert res_flags[idx + start_index] == part
174
175


Paul McCarthy's avatar
Paul McCarthy committed
176
177
178
179
180
181
182
183
184
185
186
187
188
189
def myfunc():
    print('standard output')
    print('standard error', file=sys.stderr)


def test_func_to_cmd():
    with fslsub_mockFSLDIR(), tempdir():
        cmd = fslsub.func_to_cmd(myfunc, (), {})
        jid = fslsub.submit(cmd)

        stdout, stderr = fslsub.output(jid)

        assert stdout.strip() == 'standard output'
        assert stderr.strip() == 'standard error'
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
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258


example_qstat_reply = """==============================================================
job_number:                 9985061
exec_file:                  job_scripts/9985061
owner:                      user
sge_o_home:                 /home/fs0/user
sge_o_log_name:             user
sge_o_shell:                /bin/bash
sge_o_workdir:              /home/fs0/user
account:                    sge
cwd:                        /home/fs0/user
mail_options:               a
notify:                     FALSE
job_name:                   echo
jobshare:                   0
hard_queue_list:            long.q
restart:                    y
job_args:                   test
script_file:                echo
binding:                    set linear:slots
job_type:                   binary,noshell
scheduling info:            queue instance "<some queue>" dropped because it is temporarily not available
                            queue instance "<some queue>" dropped because it is disabled
==============================================================
job_number:                 9985062
exec_file:                  job_scripts/9985062
owner:                      user
sge_o_home:                 /home/fs0/user
sge_o_log_name:             user
sge_o_shell:                /bin/bash
sge_o_workdir:              /home/fs0/user
account:                    sge
cwd:                        /home/fs0/user
mail_options:               a
notify:                     FALSE
job_name:                   echo
jobshare:                   0
hard_queue_list:            long.q
restart:                    y
job_args:                   test
script_file:                echo
binding:                    set linear:slots
job_type:                   binary,noshell
scheduling info:            queue instance "<some queue>" dropped because it is temporarily not available
                            queue instance "<some queue>" dropped because it is disabled
"""


def test_info():
    valid_job_ids = ['9985061', '9985062']
    res = fslsub._parse_qstat(','.join(valid_job_ids), example_qstat_reply)
    assert len(res) == 2
    for job_id in valid_job_ids:
        assert res[job_id] is not None
        assert res[job_id]['account'] == 'sge'
        assert res[job_id]['job_type'] == 'binary,noshell'
        assert len(res[job_id]['scheduling info'].splitlines()) == 2
        for line in res[job_id]['scheduling info'].splitlines():
            assert line.startswith('queue instance ')

    res2 = fslsub._parse_qstat(','.join(valid_job_ids + ['1']), example_qstat_reply)
    assert len(res2) == 3
    for job_id in valid_job_ids:
        assert res[job_id] == res2[job_id]
    assert res2['1'] is None

    with pytest.raises(ValueError):
        fslsub._parse_qstat(valid_job_ids[0], example_qstat_reply)
259
260
261
262
263
264
265
266
267
268
269


def _good_func():
    print('hello')


def _bad_func():
    1/0


def test_func_to_cmd():
270
    cwd = os.getcwd()
271
272
273
274
275
276
277
    with tempdir():
        for tmp_dir in (None, '.'):
            for clean in ('never', 'on_success', 'always'):
                for verbose in (False, True):
                    cmd = fslsub.func_to_cmd(_good_func, clean=clean, tmp_dir=tmp_dir, verbose=verbose)
                    fn = cmd.split()[-1]
                    assert op.exists(fn)
278
279
                    stdout, stderr, exitcode = run.run(cmd, exitcode=True, stdout=True, stderr=True,
                                                       env={"PYTHONPATH": cwd})
280
281
282
283
284
285
286
287
288
289
290
291
292
                    assert exitcode == 0
                    if clean == 'never':
                        assert op.exists(fn), "Successful job got removed, even though this was not requested"
                    else:
                        assert not op.exists(fn), f"Successful job did not get removed after run for clean = {clean}"
                    if verbose:
                        assert stdout.strip() == f'running {fn}\nhello'
                    else:
                        assert stdout.strip() == 'hello'

                cmd = fslsub.func_to_cmd(_bad_func, clean=clean, tmp_dir=tmp_dir)
                fn = cmd.split()[-1]
                assert op.exists(fn)
293
294
                stdout, stderr, exitcode = run.run(cmd, exitcode=True, stdout=True, stderr=True,
                                                   env={'PYTHONPATH': cwd})
295
296
297
298
299
                assert exitcode != 0
                if clean == 'always':
                    assert not op.exists(fn), "Failing job should always be removed if requested"
                else:
                    assert op.exists(fn), f"Failing job got removed even with clean = {clean}"