Debian Codegraph @

tests/test_action.py

raw symbols SCIP
1 import os
2 import sys
3 import io
4 import tempfile
5 import textwrap
6 import locale
7 locale # quiet pyflakes
8 from pathlib import PurePath, Path
9 from io import StringIO, BytesIO
10 from threading import Thread
11 import time
12 from sys import executable
13 from unittest.mock import Mock
14
15 import pytest
16
17 from doit import action
18 from doit.task import Task
19 from doit.exceptions import TaskError, TaskFailed
20
21
22 #path to test folder
23 TEST_PATH = os.path.dirname(__file__)
24 PROGRAM = "%s %s/sample_process.py" % (executable, TEST_PATH)
25
26
27 @pytest.fixture
28 def tmpfile(request):
29 temp = tempfile.TemporaryFile('w+', encoding="utf-8")
30 request.addfinalizer(temp.close)
31 return temp
32
33
34 ############# CmdAction
35 class TestCmdAction(object):
36 # if nothing is raised it is successful
37 def test_success(self):
38 my_action = action.CmdAction(PROGRAM)
39 got = my_action.execute()
40 assert got is None
41
42 def test_success_noshell(self):
43 my_action = action.CmdAction(PROGRAM.split(), shell=False)
44 got = my_action.execute()
45 assert got is None
46
47 def test_error(self):
48 my_action = action.CmdAction("%s 1 2 3" % PROGRAM)
49 got = my_action.execute()
50 assert isinstance(got, TaskError)
51
52 def test_env(self):
53 env = os.environ.copy()
54 env['GELKIPWDUZLOVSXE'] = '1'
55 my_action = action.CmdAction("%s check env" % PROGRAM, env=env)
56 got = my_action.execute()
57 assert got is None
58
59 def test_failure(self):
60 my_action = action.CmdAction("%s please fail" % PROGRAM)
61 got = my_action.execute()
62 assert isinstance(got, TaskFailed)
63
64 def test_str(self):
65 my_action = action.CmdAction(PROGRAM)
66 assert "Cmd: %s" % PROGRAM == str(my_action)
67
68 def test_unicode(self):
69 action_str = PROGRAM + "中文"
70 my_action = action.CmdAction(action_str)
71 assert "Cmd: %s" % action_str == str(my_action)
72
73 def test_repr(self):
74 my_action = action.CmdAction(PROGRAM)
75 expected = "<CmdAction: '%s'>" % PROGRAM
76 assert expected == repr(my_action), repr(my_action)
77
78 def test_result(self):
79 my_action = action.CmdAction("%s 1 2" % PROGRAM)
80 my_action.execute()
81 assert "12" == my_action.result
82
83 def test_values(self):
84 # for cmdActions they are empty if save_out not specified
85 my_action = action.CmdAction("%s 1 2" % PROGRAM)
86 my_action.execute()
87 assert {} == my_action.values
88
89
90 class TestCmdActionParams(object):
91 def test_invalid_param_stdout(self):
92 pytest.raises(action.InvalidTask, action.CmdAction,
93 [PROGRAM], stdout=None)
94
95 def test_changePath(self, tmpdir):
96 path = tmpdir.mkdir("foo")
97 command = '%s -c "import os; print(os.getcwd())"' % executable
98 my_action = action.CmdAction(command, cwd=path.strpath)
99 my_action.execute()
100 assert path + os.linesep == my_action.out, repr(my_action.out)
101
102 def test_noPathSet(self, tmpdir):
103 path = tmpdir.mkdir("foo")
104 command = '%s -c "import os; print(os.getcwd())"' % executable
105 my_action = action.CmdAction(command)
106 my_action.execute()
107 assert path.strpath + os.linesep != my_action.out, repr(my_action.out)
108
109
110 class TestCmdVerbosity(object):
111 # Capture stderr
112 def test_captureStderr(self):
113 cmd = "%s please fail" % PROGRAM
114 my_action = action.CmdAction(cmd)
115 got = my_action.execute()
116 assert isinstance(got, TaskFailed)
117 assert "err output on failure" == my_action.err, repr(my_action.err)
118
119 # Capture stdout
120 def test_captureStdout(self):
121 my_action = action.CmdAction("%s hi_stdout hi2" % PROGRAM)
122 my_action.execute()
123 assert "hi_stdout" == my_action.out, repr(my_action.out)
124
125 # Do not capture stderr
126 # test using a tempfile. it is not possible (at least i dont know)
127 # how to test if the output went to the parent process,
128 # faking sys.stderr with a StringIO doesnt work.
129 def test_noCaptureStderr(self, tmpfile):
130 my_action = action.CmdAction("%s please fail" % PROGRAM)
131 action_result = my_action.execute(err=tmpfile)
132 assert isinstance(action_result, TaskFailed)
133 tmpfile.seek(0)
134 got = tmpfile.read()
135 assert "err output on failure" == got, repr(got)
136 assert "err output on failure" == my_action.err, repr(my_action.err)
137
138 # Do not capture stdout
139 def test_noCaptureStdout(self, tmpfile):
140 my_action = action.CmdAction("%s hi_stdout hi2" % PROGRAM)
141 my_action.execute(out=tmpfile)
142 tmpfile.seek(0)
143 got = tmpfile.read()
144 assert "hi_stdout" == got, repr(got)
145 assert "hi_stdout" == my_action.out, repr(my_action.out)
146
147
148 class TestTaskIOCapture:
149 def test_cmd_io_capture_yes(self):
150 task = Task(name='foo', actions=[f"{PROGRAM} hi_stdout hi2"], io={'capture': True})
151 task.init_options()
152 my_action = task.actions[0]
153 got = my_action.execute()
154 assert got is None
155 assert "hi_stdout" == my_action.out
156
157 def test_cmd_io_capture_no(self):
158 task = Task(name='foo', actions=[f"{PROGRAM} hi_stdout hi2"], io={'capture': False})
159 task.init_options()
160 my_action = task.actions[0]
161 got = my_action.execute()
162 assert got is None
163 assert my_action.out is None
164
165 def test_py_io_capture_yes(self):
166 def hello():
167 print('hello')
168 task = Task(name='foo', actions=[hello], io={'capture': True})
169 task.init_options()
170 my_action = task.actions[0]
171 got = my_action.execute()
172 assert got is None
173 assert "hello\n" == my_action.out
174
175 def test_py_io_capture_no(self):
176 def hello():
177 print('hello')
178 task = Task(name='foo', actions=[hello], io={'capture': False})
179 task.init_options()
180 my_action = task.actions[0]
181 got = my_action.execute()
182 assert got is None
183 assert my_action.out is None
184
185
186 class TestCmdExpandAction(object):
187
188 def test_task_meta_reference(self):
189 cmd = "%s %s/myecho.py" % (executable, TEST_PATH)
190 cmd += " %(dependencies)s - %(changed)s - %(targets)s"
191 dependencies = ["data/dependency1", "data/dependency2"]
192 targets = ["data/target", "data/targetXXX"]
193 task = Task('Fake', [cmd], dependencies, targets)
194 task.dep_changed = ["data/dependency1"]
195 task.options = {}
196 my_action = task.actions[0]
197 assert my_action.execute() is None
198
199 got = my_action.out.split('-')
200 assert task.file_dep == set(got[0].split())
201 assert task.dep_changed == got[1].split()
202 assert targets == got[2].split()
203
204 def test_task_options(self):
205 cmd = "%s %s/myecho.py" % (executable, TEST_PATH)
206 cmd += " %(opt1)s - %(opt2)s"
207 task = Task('Fake', [cmd])
208 task.options = {'opt1':'3', 'opt2':'abc def'}
209 my_action = task.actions[0]
210 assert my_action.execute() is None
211 got = my_action.out.strip()
212 assert "3 - abc def" == got
213
214 def test_task_pos_arg(self):
215 cmd = "%s %s/myecho.py" % (executable, TEST_PATH)
216 cmd += " %(pos)s"
217 task = Task('Fake', [cmd], pos_arg='pos')
218 task.options = {}
219 task.pos_arg_val = ['hi', 'there']
220 my_action = task.actions[0]
221 assert my_action.execute() is None
222 got = my_action.out.strip()
223 assert "hi there" == got
224
225 def test_task_pos_arg_None(self):
226 # pos_arg_val is None when the task is not specified from
227 # command line but executed because it is a task_dep
228 cmd = "%s %s/myecho.py" % (executable, TEST_PATH)
229 cmd += " %(pos)s"
230 task = Task('Fake', [cmd], pos_arg='pos')
231 task.options = {}
232 my_action = task.actions[0]
233 assert my_action.execute() is None
234 got = my_action.out.strip()
235 assert "" == got
236
237 def test_callable_return_command_str(self):
238 def get_cmd(opt1, opt2):
239 cmd = "%s %s/myecho.py" % (executable, TEST_PATH)
240 return cmd + " %s - %s" % (opt1, opt2)
241 task = Task('Fake', [action.CmdAction(get_cmd)])
242 task.options = {'opt1':'3', 'opt2':'abc def'}
243 my_action = task.actions[0]
244 assert my_action.execute() is None
245 got = my_action.out.strip()
246 assert "3 - abc def" == got, repr(got)
247
248 def test_callable_tuple_return_command_str(self):
249 def get_cmd(opt1, opt2):
250 cmd = "%s %s/myecho.py" % (executable, TEST_PATH)
251 return cmd + " %s - %s" % (opt1, opt2)
252 task = Task('Fake',
253 [action.CmdAction((get_cmd, [], {'opt2':'abc def'}))])
254 task.options = {'opt1':'3'}
255 my_action = task.actions[0]
256 assert my_action.execute() is None
257 got = my_action.out.strip()
258 assert "3 - abc def" == got, repr(got)
259
260 def test_callable_invalid(self):
261 def get_cmd(blabla): pass
262 task = Task('Fake', [action.CmdAction(get_cmd)])
263 task.options = {'opt1':'3'}
264 my_action = task.actions[0]
265 got = my_action.execute()
266 assert isinstance(got, TaskError)
267
268 def test_string_list_cant_be_expanded(self):
269 cmd = [executable, "%s/myecho.py" % TEST_PATH]
270 task = Task('Fake', [cmd])
271 my_action = task.actions[0]
272 assert cmd == my_action.expand_action()
273
274 def test_list_can_contain_path(self):
275 cmd = [executable, PurePath(TEST_PATH), Path("myecho.py")]
276 task = Task('Fake', [cmd])
277 my_action = task.actions[0]
278 assert [executable, TEST_PATH, "myecho.py"] == my_action.expand_action()
279
280 def test_list_should_contain_strings_or_paths(self):
281 cmd = [executable, PurePath(TEST_PATH), 42, Path("myecho.py")]
282 task = Task('Fake', [cmd])
283 my_action = task.actions[0]
284 assert pytest.raises(action.InvalidTask, my_action.expand_action)
285
286
287 class TestCmdActionStringFormatting(object):
288
289 def test_old(self, monkeypatch):
290 monkeypatch.setattr(action.CmdAction, 'STRING_FORMAT', 'old')
291 cmd = "%s %s/myecho.py" % (executable, TEST_PATH)
292 cmd += " %(dependencies)s - %(opt1)s"
293 task = Task('Fake', [cmd], ['data/dependency1'])
294 task.options = {'opt1':'abc'}
295 my_action = task.actions[0]
296 assert my_action.execute() is None
297 got = my_action.out.strip()
298 assert "data/dependency1 - abc" == got
299
300 def test_new(self, monkeypatch):
301 monkeypatch.setattr(action.CmdAction, 'STRING_FORMAT', 'new')
302 cmd = "%s %s/myecho.py" % (executable, TEST_PATH)
303 cmd += " {dependencies} - {opt1}"
304 task = Task('Fake', [cmd], ['data/dependency1'])
305 task.options = {'opt1':'abc'}
306 my_action = task.actions[0]
307 assert my_action.execute() is None
308 got = my_action.out.strip()
309 assert "data/dependency1 - abc" == got
310
311 def test_both(self, monkeypatch):
312 monkeypatch.setattr(action.CmdAction, 'STRING_FORMAT', 'both')
313 cmd = "%s %s/myecho.py" % (executable, TEST_PATH)
314 cmd += " {dependencies} - %(opt1)s"
315 task = Task('Fake', [cmd], ['data/dependency1'])
316 task.options = {'opt1':'abc'}
317 my_action = task.actions[0]
318 assert my_action.execute() is None
319 got = my_action.out.strip()
320 assert "data/dependency1 - abc" == got
321
322
323
324 class TestCmd_print_process_output_line(object):
325 def test_non_unicode_string_error_strict(self):
326 my_action = action.CmdAction("", decode_error='strict')
327 not_unicode = BytesIO('\xa9'.encode("latin-1"))
328 realtime = Mock()
329 realtime.encoding = 'utf-8'
330 pytest.raises(UnicodeDecodeError,
331 my_action._print_process_output,
332 Mock(), not_unicode, Mock(), realtime)
333
334 def test_non_unicode_string_error_replace(self):
335 my_action = action.CmdAction("") # default is decode_error = 'replace'
336 not_unicode = BytesIO('\xa9'.encode("latin-1"))
337 realtime = Mock()
338 realtime.encoding = 'utf-8'
339 capture = StringIO()
340 my_action._print_process_output(
341 Mock(), not_unicode, capture, realtime)
342 # get the replacement char
343 expected = '�'
344 assert expected == capture.getvalue()
345
346 def test_non_unicode_string_ok(self):
347 my_action = action.CmdAction("", encoding='iso-8859-1')
348 not_unicode = BytesIO('\xa9'.encode("latin-1"))
349 realtime = Mock()
350 realtime.encoding = 'utf-8'
351 capture = StringIO()
352 my_action._print_process_output(
353 Mock(), not_unicode, capture, realtime)
354 # get the correct char from latin-1 encoding
355 expected = '©'
356 assert expected == capture.getvalue()
357
358
359 # dont test unicode if system locale doesnt support unicode
360 # see https://bitbucket.org/schettino72/doit/pull-request/11
361 @pytest.mark.skipif('locale.getlocale()[1] is None')
362 def test_unicode_string(self, tmpfile):
363 my_action = action.CmdAction("")
364 unicode_in = tempfile.TemporaryFile('w+b')
365 unicode_in.write(" 中文".encode('utf-8'))
366 unicode_in.seek(0)
367 my_action._print_process_output(
368 Mock(), unicode_in, Mock(), tmpfile)
369
370 @pytest.mark.skipif('locale.getlocale()[1] is None')
371 def test_unicode_string2(self, tmpfile):
372 # this \uXXXX has a different behavior!
373 my_action = action.CmdAction("")
374 unicode_in = tempfile.TemporaryFile('w+b')
375 unicode_in.write(" 中文 \u2018".encode('utf-8'))
376 unicode_in.seek(0)
377 my_action._print_process_output(
378 Mock(), unicode_in, Mock(), tmpfile)
379
380 def test_line_buffered_output(self):
381 my_action = action.CmdAction("")
382 out, inp = os.pipe()
383 out, inp = os.fdopen(out, 'rb'), os.fdopen(inp, 'wb')
384 inp.write('abcd\nline2'.encode('utf-8'))
385 inp.flush()
386 capture = StringIO()
387
388 thread = Thread(target=my_action._print_process_output,
389 args=(Mock(), out, capture, None))
390 thread.start()
391 time.sleep(0.1)
392 try:
393 got = capture.getvalue()
394 # 'line2' is not captured because of line buffering
395 assert 'abcd\n' == got
396 print('asserted')
397 finally:
398 inp.close()
399
400 def test_unbuffered_output(self):
401 my_action = action.CmdAction("", buffering=1)
402 out, inp = os.pipe()
403 out, inp = os.fdopen(out, 'rb'), os.fdopen(inp, 'wb')
404 inp.write('abcd\nline2'.encode('utf-8'))
405 inp.flush()
406 capture = StringIO()
407
408 thread = Thread(target=my_action._print_process_output,
409 args=(Mock(), out, capture, None))
410 thread.start()
411 time.sleep(0.1)
412 try:
413 got = capture.getvalue()
414 assert 'abcd\nline2' == got
415 finally:
416 inp.close()
417
418
419 def test_unbuffered_env(self, monkeypatch):
420 my_action = action.CmdAction("", buffering=1)
421 proc_mock = Mock()
422 proc_mock.configure_mock(returncode=0)
423 popen_mock = Mock(return_value=proc_mock)
424 from doit.action import subprocess
425 monkeypatch.setattr(subprocess, 'Popen', popen_mock)
426 my_action._print_process_output = Mock()
427 my_action.execute()
428 env = popen_mock.call_args[-1]['env']
429 assert env and env.get('PYTHONUNBUFFERED', False) == '1'
430
431
432
433 class TestCmdSaveOuput(object):
434 def test_success(self):
435 TEST_PATH = os.path.dirname(__file__)
436 PROGRAM = "%s %s/sample_process.py" % (executable, TEST_PATH)
437 my_action = action.CmdAction(PROGRAM + " x1 x2", save_out='out')
438 my_action.execute()
439 assert {'out': 'x1'} == my_action.values
440
441
442
443 class FakeStream():
444 def __init__(self, tty, fileno=None):
445 self.tty = tty
446 self._fileno = fileno
447 def isatty(self):
448 return self.tty
449 def fileno(self):
450 return self._fileno
451
452 class TestWriter(object):
453 def test_write(self):
454 w1 = StringIO()
455 w2 = StringIO()
456 writer = action.Writer(w1, w2)
457 writer.flush() # make sure flush is supported
458 writer.write("hello")
459 assert "hello" == w1.getvalue()
460 assert "hello" == w2.getvalue()
461
462 def test_isatty_true(self):
463 w1 = StringIO()
464 writer = action.Writer(w1)
465 w2 = FakeStream(True)
466 writer.add_writer(w2, is_original=True)
467 assert writer.isatty()
468
469 def test_isatty_false(self):
470 # not a tty even if stream is a tty but not marked as original stream
471 w1 = FakeStream(True)
472 w1.isatty = lambda: True
473 writer = action.Writer(w1)
474 assert not writer.isatty()
475
476 def test_fileno(self):
477 w1 = StringIO()
478 w2 = FakeStream(True, 32)
479 writer = action.Writer()
480 writer.add_writer(w1)
481 writer.add_writer(w2, is_original=True)
482 assert writer.isatty()
483 assert 32 == writer.fileno()
484
485 def test_fileno_not_supported(self):
486 w1 = FakeStream(True, 11)
487 writer = action.Writer(w1)
488 pytest.raises(io.UnsupportedOperation, writer.fileno)
489
490
491 ############# PythonAction
492
493 class TestPythonAction(object):
494
495 def test_success_bool(self):
496 def success_sample():return True
497 my_action = action.PythonAction(success_sample)
498 # nothing raised it was successful
499 my_action.execute()
500
501 def test_success_None(self):
502 def success_sample():return
503 my_action = action.PythonAction(success_sample)
504 # nothing raised it was successful
505 my_action.execute()
506
507 def test_success_str(self):
508 def success_sample():return ""
509 my_action = action.PythonAction(success_sample)
510 # nothing raised it was successful
511 my_action.execute()
512
513 def test_success_dict(self):
514 def success_sample():return {}
515 my_action = action.PythonAction(success_sample)
516 # nothing raised it was successful
517 my_action.execute()
518
519 def test_error_object(self):
520 # anthing but None, bool, string or dict
521 def error_sample(): return object()
522 my_action = action.PythonAction(error_sample)
523 got = my_action.execute()
524 assert isinstance(got, TaskError)
525
526 def test_error_taskfail(self):
527 # should get the same exception as was returned from the
528 # user's function
529 def error_sample(): return TaskFailed("too bad")
530 ye_olde_action = action.PythonAction(error_sample)
531 ret = ye_olde_action.execute()
532 assert isinstance(ret, TaskFailed)
533 assert str(ret).endswith("too bad\n")
534
535 def test_error_taskerror(self):
536 def error_sample(): return TaskError("so sad")
537 ye_olde_action = action.PythonAction(error_sample)
538 ret = ye_olde_action.execute()
539 assert str(ret).endswith("so sad\n")
540
541 def test_error_exception(self):
542 def error_sample(): raise Exception("asdf")
543 my_action = action.PythonAction(error_sample)
544 got = my_action.execute()
545 assert isinstance(got, TaskError)
546
547 def test_fail_bool(self):
548 def fail_sample():return False
549 my_action = action.PythonAction(fail_sample)
550 got = my_action.execute()
551 assert isinstance(got, TaskFailed)
552
553 # any callable should work, not only functions
554 def test_callable_obj(self):
555 class CallMe:
556 def __call__(self):
557 return False
558
559 my_action = action.PythonAction(CallMe())
560 got = my_action.execute()
561 assert isinstance(got, TaskFailed)
562
563
564 # helper to test callable with parameters
565 def _func_par(self,par1,par2,par3=5):
566 if par1 == par2 and par3 > 10:
567 return True
568 else:
569 return False
570
571
572 def test_init(self):
573 # default values
574 action1 = action.PythonAction(self._func_par)
575 assert action1.args == []
576 assert action1.kwargs == {}
577
578 # not a callable
579 pytest.raises(action.InvalidTask, action.PythonAction, "abc")
580 # args not a list
581 pytest.raises(action.InvalidTask, action.PythonAction, self._func_par, "c")
582 # kwargs not a list
583 pytest.raises(action.InvalidTask, action.PythonAction,
584 self._func_par, None, "a")
585
586 # cant use a class as callable
587 def test_init_callable_class(self):
588 class CallMe(object):
589 pass
590 pytest.raises(action.InvalidTask, action.PythonAction, CallMe)
591
592 # cant use built-ins
593 def test_init_callable_builtin(self):
594 pytest.raises(action.InvalidTask, action.PythonAction, any)
595
596 def test_functionParametersArgs(self):
597 my_action = action.PythonAction(self._func_par,args=(2,2,25))
598 my_action.execute()
599
600 def test_functionParametersKwargs(self):
601 my_action = action.PythonAction(self._func_par,
602 kwargs={'par1':2,'par2':2,'par3':25})
603 my_action.execute()
604
605 def test_functionParameters(self):
606 my_action = action.PythonAction(self._func_par,args=(2,2),
607 kwargs={'par3':25})
608 my_action.execute()
609
610 def test_functionParametersFail(self):
611 my_action = action.PythonAction(self._func_par, args=(2,3),
612 kwargs={'par3':25})
613 got = my_action.execute()
614 assert isinstance(got, TaskFailed)
615
616 def test_str(self):
617 def str_sample(): return True
618 my_action = action.PythonAction(str_sample)
619 assert "Python: function" in str(my_action)
620 assert "str_sample" in str(my_action)
621
622 def test_repr(self):
623 def repr_sample(): return True
624 my_action = action.PythonAction(repr_sample)
625 assert "<PythonAction: '%s'>" % repr(repr_sample) == repr(my_action)
626
627 def test_result(self):
628 def vvv(): return "my value"
629 my_action = action.PythonAction(vvv)
630 my_action.execute()
631 assert "my value" == my_action.result
632
633 def test_result_dict(self):
634 def vvv(): return {'xxx': "my value"}
635 my_action = action.PythonAction(vvv)
636 my_action.execute()
637 assert {'xxx': "my value"} == my_action.result
638
639 def test_values(self):
640 def vvv(): return {'x': 5, 'y':10}
641 my_action = action.PythonAction(vvv)
642 my_action.execute()
643 assert {'x': 5, 'y':10} == my_action.values
644
645
646 class TestPythonVerbosity(object):
647 def write_stderr(self):
648 sys.stderr.write("this is stderr S\n")
649
650 def write_stdout(self):
651 sys.stdout.write("this is stdout S\n")
652
653 def test_captureStderr(self):
654 my_action = action.PythonAction(self.write_stderr)
655 my_action.execute()
656 assert "this is stderr S\n" == my_action.err, repr(my_action.err)
657
658 def test_captureStdout(self):
659 my_action = action.PythonAction(self.write_stdout)
660 my_action.execute()
661 assert "this is stdout S\n" == my_action.out, repr(my_action.out)
662
663 def test_noCaptureStderr(self, capsys):
664 my_action = action.PythonAction(self.write_stderr)
665 my_action.execute(err=sys.stderr)
666 got = capsys.readouterr()[1]
667 assert "this is stderr S\n" == got, repr(got)
668
669 def test_noCaptureStdout(self, capsys):
670 my_action = action.PythonAction(self.write_stdout)
671 my_action.execute(out=sys.stdout)
672 got = capsys.readouterr()[0]
673 assert "this is stdout S\n" == got, repr(got)
674
675 def test_redirectStderr(self):
676 tmpfile = tempfile.TemporaryFile('w+')
677 my_action = action.PythonAction(self.write_stderr)
678 my_action.execute(err=tmpfile)
679 tmpfile.seek(0)
680 got = tmpfile.read()
681 tmpfile.close()
682 assert "this is stderr S\n" == got, got
683
684 def test_redirectStdout(self):
685 tmpfile = tempfile.TemporaryFile('w+')
686 my_action = action.PythonAction(self.write_stdout)
687 my_action.execute(out=tmpfile)
688 tmpfile.seek(0)
689 got = tmpfile.read()
690 tmpfile.close()
691 assert "this is stdout S\n" == got, got
692
693
694 class TestPythonActionPrepareKwargsMeta(object):
695
696 def test_no_extra_args(self):
697 # no error trying to inject values
698 def py_callable():
699 return True
700 task = Task('Fake', [py_callable], file_dep=['dependencies'])
701 task.options = {}
702 my_action = task.actions[0]
703 my_action.execute()
704
705 def test_keyword_extra_args(self):
706 got = []
707 def py_callable(arg=None, **kwargs):
708 got.append(kwargs)
709 my_task = Task('Fake', [(py_callable, (), {'b': 4})],
710 file_dep=['dependencies'])
711 my_task.options = {'foo': 'bar'}
712 my_action = my_task.actions[0]
713 my_action.execute()
714 # meta args do not leak into kwargs
715 assert got == [{'foo': 'bar', 'b': 4}]
716
717
718 def test_named_extra_args(self):
719 got = []
720 def py_callable(targets, dependencies, changed, task):
721 got.append(targets)
722 got.append(dependencies)
723 got.append(changed)
724 got.append(task)
725 task = Task('Fake', [py_callable], file_dep=['dependencies'],
726 targets=['targets'])
727 task.dep_changed = ['changed']
728 task.options = {}
729 my_action = task.actions[0]
730 my_action.execute()
731 assert got == [['targets'], ['dependencies'], ['changed'],
732 task]
733
734 def test_mixed_args(self):
735 got = []
736 def py_callable(a, b, changed):
737 got.append(a)
738 got.append(b)
739 got.append(changed)
740 task = Task('Fake', [(py_callable, ('a', 'b'))])
741 task.options = {}
742 task.dep_changed = ['changed']
743 my_action = task.actions[0]
744 my_action.execute()
745 assert got == ['a', 'b', ['changed']]
746
747 def test_extra_arg_overwritten(self):
748 got = []
749 def py_callable(a, b, changed):
750 got.append(a)
751 got.append(b)
752 got.append(changed)
753 task = Task('Fake', [(py_callable, ('a', 'b', 'c'))])
754 task.dep_changed = ['changed']
755 task.options = {}
756 my_action = task.actions[0]
757 my_action.execute()
758 assert got == ['a', 'b', 'c']
759
760 def test_extra_kwarg_overwritten(self):
761 got = []
762 def py_callable(a, b, **kwargs):
763 got.append(a)
764 got.append(b)
765 got.append(kwargs['changed'])
766 task = Task('Fake', [(py_callable, ('a', 'b'), {'changed': 'c'})])
767 task.options = {}
768 task.dep_changed = ['changed']
769 my_action = task.actions[0]
770 my_action.execute()
771 assert got == ['a', 'b', 'c']
772
773 def test_meta_arg_default_disallowed(self):
774 def py_callable(a, b, changed=None): pass
775 task = Task('Fake', [(py_callable, ('a', 'b'))])
776 task.options = {}
777 task.dep_changed = ['changed']
778 my_action = task.actions[0]
779 pytest.raises(action.InvalidTask, my_action.execute)
780
781 def test_callable_obj(self):
782 got = []
783 class CallMe(object):
784 def __call__(self, a, b, changed):
785 got.append(a)
786 got.append(b)
787 got.append(changed)
788 task = Task('Fake', [(CallMe(), ('a', 'b'))])
789 task.options = {}
790 task.dep_changed = ['changed']
791 my_action = task.actions[0]
792 my_action.execute()
793 assert got == ['a', 'b', ['changed']]
794
795 def test_method(self):
796 got = []
797 class CallMe(object):
798 def xxx(self, a, b, changed):
799 got.append(a)
800 got.append(b)
801 got.append(changed)
802 task = Task('Fake', [(CallMe().xxx, ('a', 'b'))])
803 task.options = {}
804 task.dep_changed = ['changed']
805 my_action = task.actions[0]
806 my_action.execute()
807 assert got == ['a', 'b', ['changed']]
808
809
810 def test_task_options(self):
811 got = []
812 def py_callable(opt1, opt3):
813 got.append(opt1)
814 got.append(opt3)
815 task = Task('Fake', [py_callable])
816 task.options = {'opt1':'1', 'opt2':'abc def', 'opt3':3}
817 my_action = task.actions[0]
818 my_action.execute()
819 assert ['1',3] == got, repr(got)
820
821 def test_task_pos_arg(self):
822 got = []
823 def py_callable(pos):
824 got.append(pos)
825 task = Task('Fake', [py_callable], pos_arg='pos')
826 task.options = {}
827 task.pos_arg_val = ['hi', 'there']
828 my_action = task.actions[0]
829 my_action.execute()
830 assert [['hi', 'there']] == got, repr(got)
831
832 def test_option_default_allowed(self):
833 got = []
834 def py_callable(opt2='ABC'):
835 got.append(opt2)
836 task = Task('Fake', [py_callable])
837 task.options = {'opt2':'123'}
838 my_action = task.actions[0]
839 my_action.execute()
840 assert ['123'] == got, repr(got)
841
842
843 def test_kwonlyargs_minimal(self):
844 got = []
845 scope = {'got': got}
846 exec(textwrap.dedent('''
847 def py_callable(*args, kwonly=None):
848 got.append(args)
849 got.append(kwonly)
850 '''), scope)
851 task = Task('Fake', [(scope['py_callable'], (1, 2, 3), {'kwonly': 4})])
852 task.options = {}
853 my_action = task.actions[0]
854 my_action.execute()
855 assert [(1, 2, 3), 4] == got, repr(got)
856
857
858 def test_kwonlyargs_full(self):
859 got = []
860 scope = {'got': got}
861 exec(textwrap.dedent('''
862 def py_callable(pos, *args, kwonly=None, **kwargs):
863 got.append(pos)
864 got.append(args)
865 got.append(kwonly)
866 got.append(kwargs['foo'])
867 '''), scope)
868 task = Task('Fake', [
869 (scope['py_callable'], [1,2,3], {'kwonly': 4, 'foo': 5})])
870 task.options = {}
871 my_action = task.actions[0]
872 my_action.execute()
873 assert [1, (2, 3), 4, 5] == got, repr(got)
874
875 def test_action_modifies_task_but_not_attrs(self):
876 def py_callable(targets, dependencies, changed, task):
877 targets.append('new_target')
878 dependencies.append('new_dependency')
879 changed.append('new_changed')
880 task.file_dep.add('dep2')
881 my_task = Task('Fake', [py_callable], file_dep=['dependencies'],
882 targets=['targets'])
883 my_task.dep_changed = ['changed']
884 my_task.options = {}
885 my_action = my_task.actions[0]
886 my_action.execute()
887
888 assert my_task.file_dep == set(['dependencies', 'dep2'])
889 assert my_task.targets == ['targets']
890 assert my_task.dep_changed == ['changed']
891
892
893 ##############
894
895
896 class TestCreateAction(object):
897 class TaskStub(object):
898 name = 'stub'
899 mytask = TaskStub()
900
901 def testBaseAction(self):
902 class Sample(action.BaseAction): pass
903 my_action = action.create_action(Sample(), self.mytask, 'actions')
904 assert isinstance(my_action, Sample)
905 assert self.mytask == my_action.task
906
907 def testStringAction(self):
908 my_action = action.create_action("xpto 14 7", self.mytask, 'actions')
909 assert isinstance(my_action, action.CmdAction)
910 assert my_action.shell == True
911
912 def testListStringAction(self):
913 my_action = action.create_action(["xpto", 14, 7], self.mytask, 'actions')
914 assert isinstance(my_action, action.CmdAction)
915 assert my_action.shell == False
916
917 def testMethodAction(self):
918 def dumb(): return
919 my_action = action.create_action(dumb, self.mytask, 'actions')
920 assert isinstance(my_action, action.PythonAction)
921
922 def testTupleAction(self):
923 def dumb(): return
924 my_action = action.create_action((dumb,[1,2],{'a':5}), self.mytask,
925 'actions')
926 assert isinstance(my_action, action.PythonAction)
927
928 def testTupleActionMoreThanThreeElements(self):
929 def dumb(): return
930 expected = "Task 'stub': invalid 'actions' tuple length"
931 with pytest.raises(action.InvalidTask, match=expected):
932 action.create_action((dumb,[1,2],{'a':5},'oo'), self.mytask,
933 'actions')
934
935 def testInvalidActionNone(self):
936 expected = "Task 'stub': invalid 'actions' type. got: None"
937 with pytest.raises(action.InvalidTask, match=expected):
938 action.create_action(None, self.mytask, 'actions')
939
940 def testInvalidActionObject(self):
941 expected = "Task 'stub': invalid 'actions' type. got: <"
942 with pytest.raises(action.InvalidTask, match=expected):
943 action.create_action(self, self.mytask, 'actions')
944
945 def test_invalid_action_task_param_name(self):
946 expected = "Task 'stub': invalid 'clean' type. got: True"
947 with pytest.raises(action.InvalidTask, match=expected):
948 action.create_action(True, self.mytask, 'clean')