File: sets_test.py

package info (click to toggle)
paleomix 1.3.10-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 3,156 kB
  • sloc: python: 21,423; sh: 182; makefile: 37
file content (403 lines) | stat: -rw-r--r-- 12,133 bytes parent folder | download | duplicates (4)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
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
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
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
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
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
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
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
401
402
403
#!/usr/bin/python3
#
# Copyright (c) 2012 Mikkel Schubert <MikkelSch@gmail.com>
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in all
# copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
# SOFTWARE.
#
from unittest.mock import call, Mock

import pytest

import paleomix.atomiccmd.pprint
from paleomix.atomiccmd.command import AtomicCmd, CmdError
from paleomix.atomiccmd.sets import ParallelCmds, SequentialCmds

_SET_CLASSES = (ParallelCmds, SequentialCmds)

###############################################################################
###############################################################################
# Properties with same expected behavior for both Parallel/SequentialCmds


@pytest.mark.parametrize("cls", _SET_CLASSES)
def test_atomicsets__properties(cls):
    cmd_mock_1 = AtomicCmd(
        ("true",),
        CHECK_A=id,
        EXEC_1="false",
        IN_1="/foo/bar/in_1.file",
        IN_2="/foo/bar/in_2.file",
        OUT_1="/bar/foo/out",
        TEMP_OUT_1="out.log",
        AUX_A="/aux/fA",
        AUX_B="/aux/fB",
    )
    cmd_mock_2 = AtomicCmd(
        ("false",),
        CHECK_A=list,
        EXEC_1="echo",
        EXEC_2="java",
        IN_1="/foo/bar/in.file",
        OUT_1="out.txt",
    )

    obj = cls([cmd_mock_1, cmd_mock_2])
    assert obj.executables == cmd_mock_1.executables | cmd_mock_2.executables
    assert obj.requirements == cmd_mock_1.requirements | cmd_mock_2.requirements
    assert obj.input_files == cmd_mock_1.input_files | cmd_mock_2.input_files
    assert obj.output_files == cmd_mock_1.output_files | cmd_mock_2.output_files
    assert (
        obj.auxiliary_files == cmd_mock_1.auxiliary_files | cmd_mock_2.auxiliary_files
    )
    assert obj.expected_temp_files == frozenset(["out", "out.txt"])
    assert (
        obj.optional_temp_files
        == cmd_mock_1.optional_temp_files | cmd_mock_2.optional_temp_files
    )


_NO_CLOBBERING_KWARGS = (
    ({"OUT_A": "/foo/out.txt"}, {"OUT_B": "/bar/out.txt"}),
    ({"OUT_A": "/foo/out.txt"}, {"TEMP_OUT_B": "out.txt"}),
    ({"OUT_A": "/foo/out.txt"}, {"OUT_STDOUT": "/bar/out.txt"}),
    ({"OUT_A": "/foo/out.txt"}, {"TEMP_OUT_STDOUT": "out.txt"}),
    ({"OUT_A": "/foo/out.txt"}, {"OUT_STDERR": "/bar/out.txt"}),
    ({"OUT_A": "/foo/out.txt"}, {"TEMP_OUT_STDERR": "out.txt"}),
)

# Ensure that commands in a set doesn't clobber eachothers OUT files
@pytest.mark.parametrize("cls", _SET_CLASSES)
@pytest.mark.parametrize("kwargs_1, kwargs_2", _NO_CLOBBERING_KWARGS)
def test_atomicsets__no_clobbering(cls, kwargs_1, kwargs_2):
    cmd_1 = AtomicCmd("true", **kwargs_1)
    cmd_2 = AtomicCmd("true", **kwargs_2)
    with pytest.raises(CmdError):
        cls([cmd_1, cmd_2])


###############################################################################
###############################################################################
# Functions with same expected behavior for both Parallel/SequentialCmds


@pytest.mark.parametrize("cls", _SET_CLASSES)
def test_atomicsets__commit(cls):
    mock = Mock()
    cmd_1 = AtomicCmd(["ls"])
    cmd_1.commit = mock.commit_1
    cmd_2 = AtomicCmd(["ls"])
    cmd_2.commit = mock.commit_2
    cmd_3 = AtomicCmd(["ls"])
    cmd_3.commit = mock.commit_3

    cls((cmd_1, cmd_2, cmd_3)).commit("xTMPx")

    assert mock.mock_calls == [
        call.commit_1("xTMPx"),
        call.commit_2("xTMPx"),
        call.commit_3("xTMPx"),
    ]


@pytest.mark.parametrize("cls", _SET_CLASSES)
def test_atomicsets__commit__remove_files_on_failure(tmp_path, cls):
    (tmp_path / "tmp").mkdir()
    out_path = tmp_path / "out"

    cmd_1 = AtomicCmd(["touch", "%(OUT_FILE)s"], OUT_FILE=str(out_path / "file1"))
    cmd_2 = AtomicCmd(["touch", "%(OUT_FILE)s"], OUT_FILE=str(out_path / "file2"))
    cmd_2.commit = Mock()
    cmd_2.commit.side_effect = OSError()

    cmdset = cls((cmd_1, cmd_2))
    cmdset.run(str(tmp_path / "tmp"))
    assert cmdset.join() == [0, 0]

    with pytest.raises(OSError):
        cmdset.commit(str(tmp_path / "tmp"))

    tmp_files = [it.name for it in (tmp_path / "tmp").iterdir()]
    assert "file1" not in tmp_files
    assert "file2" in tmp_files

    assert list((tmp_path / "out").iterdir()) == []


@pytest.mark.parametrize("cls", _SET_CLASSES)
def test_atomicsets__stdout(cls):
    cmds = cls([AtomicCmd("ls")])
    with pytest.raises(CmdError):
        cmds.stdout


@pytest.mark.parametrize("cls", _SET_CLASSES)
def test_atomicsets__terminate(cls):
    mock = Mock()
    cmd_1 = AtomicCmd(["ls"])
    cmd_1.terminate = mock.terminate_1
    cmd_2 = AtomicCmd(["ls"])
    cmd_2.terminate = mock.terminate_2
    cmd_3 = AtomicCmd(["ls"])
    cmd_3.terminate = mock.terminate_3

    cmds = cls((cmd_3, cmd_2, cmd_1))
    cmds.terminate()

    assert mock.mock_calls == [
        call.terminate_3(),
        call.terminate_2(),
        call.terminate_1(),
    ]


@pytest.mark.parametrize("cls", _SET_CLASSES)
def test_atomicsets__str__(cls):
    cmds = cls([AtomicCmd("ls")])
    assert paleomix.atomiccmd.pprint.pformat(cmds) == str(cmds)


@pytest.mark.parametrize("cls", _SET_CLASSES)
def test_atomicsets__duplicate_cmds(cls):
    cmd_1 = AtomicCmd("true")
    cmd_2 = AtomicCmd("false")
    with pytest.raises(ValueError):
        cls([cmd_1, cmd_2, cmd_1])


###############################################################################
###############################################################################
# Parallel commands


def test_parallel_commands__run():
    mock = Mock()
    cmd_1 = AtomicCmd(["ls"])
    cmd_1.run = mock.run_1
    cmd_2 = AtomicCmd(["ls"])
    cmd_2.run = mock.run_2
    cmd_3 = AtomicCmd(["ls"])
    cmd_3.run = mock.run_3

    cmds = ParallelCmds((cmd_1, cmd_2, cmd_3))
    cmds.run("xTMPx")

    assert mock.mock_calls == [
        call.run_1("xTMPx"),
        call.run_2("xTMPx"),
        call.run_3("xTMPx"),
    ]


@pytest.mark.parametrize("value", (True, False))
def test_parallel_commands__ready_single(value):
    cmd = AtomicCmd(["ls"])
    cmd.ready = Mock()
    cmd.ready.return_value = value
    cmds = ParallelCmds([cmd])
    assert cmds.ready() == value

    assert cmd.ready.mock_calls


_READY_TWO_VALUES = (
    (True, True, True),
    (False, True, False),
    (True, False, False),
    (False, False, False),
)


@pytest.mark.parametrize("first, second, result", _READY_TWO_VALUES)
def test_parallel_commands__ready_two(first, second, result):
    cmd_1 = AtomicCmd(["ls"])
    cmd_1.ready = Mock()
    cmd_1.ready.return_value = first

    cmd_2 = AtomicCmd(["ls"])
    cmd_2.ready = Mock()
    cmd_2.ready.return_value = second
    cmds = ParallelCmds([cmd_1, cmd_2])
    assert cmds.ready() == result

    assert cmd_1.ready.mock_calls
    assert bool(first) == bool(cmd_2.ready.call_count)


def test_parallel_commands__join_before_run():
    mock = Mock()
    cmd_1 = AtomicCmd(["ls"])
    cmd_1.join = mock.join_1
    cmd_2 = AtomicCmd(["ls"])
    cmd_2.join = mock.join_2
    cmd_3 = AtomicCmd(["ls"])
    cmd_3.join = mock.join_3

    cmds = ParallelCmds((cmd_3, cmd_2, cmd_1))
    assert cmds.join() == [None, None, None]

    assert mock.mock_calls == []


def test_parallel_commands__join_after_run(tmp_path):
    cmds = ParallelCmds([AtomicCmd("true") for _ in range(3)])
    cmds.run(str(tmp_path))
    assert cmds.join() == [0, 0, 0]


def _setup_mocks_for_failure(*do_mocks):
    results = []
    for do_mock in do_mocks:
        if do_mock:
            mock = AtomicCmd(("sleep", 10))
        else:
            mock = AtomicCmd("false")
        results.append(mock)
    return results


def test_parallel_commands__join_failure_1(tmp_path):
    mocks = _setup_mocks_for_failure(False, True, True)
    cmds = ParallelCmds(mocks)
    cmds.run(str(tmp_path))
    assert cmds.join() == [1, "SIGTERM", "SIGTERM"]


def test_parallel_commands__join_failure_2(tmp_path):
    mocks = _setup_mocks_for_failure(True, False, True)
    cmds = ParallelCmds(mocks)
    cmds.run(str(tmp_path))
    assert cmds.join() == ["SIGTERM", 1, "SIGTERM"]


def test_parallel_commands__join_failure_3(tmp_path):
    mocks = _setup_mocks_for_failure(True, True, False)
    cmds = ParallelCmds(mocks)
    cmds.run(str(tmp_path))
    assert cmds.join() == ["SIGTERM", "SIGTERM", 1]


def test_parallel_commands__reject_sequential():
    command = AtomicCmd(["ls"])
    seqcmd = SequentialCmds([command])
    with pytest.raises(CmdError):
        ParallelCmds([seqcmd])


def test_parallel_commands__accept_parallel():
    command = AtomicCmd(["ls"])
    parcmd = ParallelCmds([command])
    ParallelCmds([parcmd])


def test_parallel_commands__reject_noncommand():
    with pytest.raises(CmdError):
        ParallelCmds([object()])


def test_parallel_commands__reject_empty_commandset():
    with pytest.raises(CmdError):
        ParallelCmds([])


###############################################################################
###############################################################################
# Sequential commands


def test_sequential_commands__atomiccmds():
    mock = Mock()
    cmd_1 = AtomicCmd(["ls"])
    cmd_1.run = mock.run_1
    cmd_1.join = mock.join_1
    cmd_1.join.return_value = [0]
    cmd_2 = AtomicCmd(["ls"])
    cmd_2.run = mock.run_2
    cmd_2.join = mock.join_2
    cmd_2.join.return_value = [0]
    cmd_3 = AtomicCmd(["ls"])
    cmd_3.run = mock.run_3
    cmd_3.join = mock.join_3
    cmd_3.join.return_value = [0]

    cmds = SequentialCmds((cmd_1, cmd_2, cmd_3))
    assert not cmds.ready()
    cmds.run("xTMPx")
    assert cmds.ready()
    assert cmds.join() == [0, 0, 0]

    assert mock.mock_calls == [
        call.run_1("xTMPx"),
        call.join_1(),
        call.run_2("xTMPx"),
        call.join_2(),
        call.run_3("xTMPx"),
        call.join_3(),
        call.join_1(),
        call.join_2(),
        call.join_3(),
    ]


def test_sequential_commands__abort_on_error_1(tmp_path):
    cmd_1 = AtomicCmd("false")
    cmd_2 = AtomicCmd(("sleep", 10))
    cmd_3 = AtomicCmd(("sleep", 10))
    cmds = SequentialCmds([cmd_1, cmd_2, cmd_3])
    cmds.run(str(tmp_path))
    assert cmds.join() == [1, None, None]


def test_sequential_commands__abort_on_error_2(tmp_path):
    cmd_1 = AtomicCmd("true")
    cmd_2 = AtomicCmd("false")
    cmd_3 = AtomicCmd(("sleep", 10))
    cmds = SequentialCmds([cmd_1, cmd_2, cmd_3])
    cmds.run(str(tmp_path))
    assert cmds.join() == [0, 1, None]


def test_sequential_commands__abort_on_error_3(tmp_path):
    cmd_1 = AtomicCmd("true")
    cmd_2 = AtomicCmd("true")
    cmd_3 = AtomicCmd("false")
    cmds = SequentialCmds([cmd_1, cmd_2, cmd_3])
    cmds.run(str(tmp_path))
    assert cmds.join() == [0, 0, 1]


def test_sequential_commands__accept_parallel():
    command = AtomicCmd(["ls"])
    parcmd = ParallelCmds([command])
    SequentialCmds([parcmd])


def test_sequential_commands__accept_sequential():
    command = AtomicCmd(["ls"])
    seqcmd = SequentialCmds([command])
    SequentialCmds([seqcmd])


def test_sequential_commands__reject_noncommand():
    with pytest.raises(CmdError):
        SequentialCmds([object()])


def test_sequential_commands__reject_empty_commandset():
    with pytest.raises(CmdError):
        SequentialCmds([])