Debian Codegraph @

tests/test_loader.py

raw symbols SCIP
1 import os
2 import inspect
3 from operator import attrgetter
4
5 import pytest
6
7 from doit.exceptions import InvalidDodoFile, InvalidCommand
8 from doit.task import InvalidTask, DelayedLoader, Task
9 from doit.loader import flat_generator, get_module
10 from doit.loader import load_tasks, load_doit_config, generate_tasks
11 from doit.loader import create_after, task_params
12
13
14 class TestFlatGenerator(object):
15 def test_nested(self):
16 def myg(items):
17 for x in items:
18 yield x
19 flat = flat_generator(myg([1, myg([2, myg([3, myg([4, myg([5])])])])]))
20 assert [1,2,3,4,5] == [f[0] for f in flat]
21
22
23 class TestGetModule(object):
24 def testAbsolutePath(self, restore_cwd):
25 fileName = os.path.join(os.path.dirname(__file__),"loader_sample.py")
26 dodo_module = get_module(fileName)
27 assert hasattr(dodo_module, 'task_xxx1')
28
29 def testRelativePath(self, restore_cwd):
30 # test relative import but test should still work from any path
31 # so change cwd.
32 this_path = os.path.join(os.path.dirname(__file__),'..')
33 os.chdir(os.path.abspath(this_path))
34 fileName = "tests/loader_sample.py"
35 dodo_module = get_module(fileName)
36 assert hasattr(dodo_module, 'task_xxx1')
37
38 def testWrongFileName(self):
39 fileName = os.path.join(os.path.dirname(__file__),"i_dont_exist.py")
40 pytest.raises(InvalidDodoFile, get_module, fileName)
41
42 def testInParentDir(self, restore_cwd):
43 os.chdir(os.path.join(os.path.dirname(__file__), "data"))
44 fileName = "loader_sample.py"
45 pytest.raises(InvalidDodoFile, get_module, fileName)
46 get_module(fileName, seek_parent=True)
47 # cwd is changed to location of dodo.py
48 assert os.getcwd() == os.path.dirname(os.path.abspath(fileName))
49
50 def testWrongFileNameInParentDir(self, restore_cwd):
51 os.chdir(os.path.join(os.path.dirname(__file__), "data"))
52 fileName = os.path.join("i_dont_exist.py")
53 pytest.raises(InvalidDodoFile, get_module, fileName, seek_parent=True)
54
55 def testInvalidCwd(self, restore_cwd):
56 fileName = os.path.join(os.path.dirname(__file__),"loader_sample.py")
57 cwd = os.path.join(os.path.dirname(__file__), "dataX")
58 pytest.raises(InvalidCommand, get_module, fileName, cwd)
59
60
61 class TestLoadTasks(object):
62
63 @pytest.fixture
64 def dodo(self):
65 def task_xxx1():
66 """task doc"""
67 return {'actions':['do nothing']}
68
69 def task_yyy2():
70 return {'actions':None}
71
72 def task_meta():
73 return {
74 'actions' : ['do nothing'],
75 'meta' : { 'a' : ['b', 'c']},
76 }
77
78 def bad_seed(): pass
79 task_nono = 5
80 task_nono # pyflakes
81 return locals()
82
83 def testNormalCase(self, dodo):
84 task_list = load_tasks(dodo)
85 assert 3 == len(task_list)
86 assert 'xxx1' == task_list[0].name
87 assert 'yyy2' == task_list[1].name
88 assert 'meta' == task_list[2].name
89
90 def testCreateAfterDecorator(self):
91 @create_after('yyy2')
92 def task_zzz3(): # pragma: no cover
93 pass
94
95 # create_after annotates the function
96 assert isinstance(task_zzz3.doit_create_after, DelayedLoader)
97 assert task_zzz3.doit_create_after.task_dep == 'yyy2'
98
99 def testInitialLoadDelayedTask(self, dodo):
100 @create_after('yyy2')
101 def task_zzz3(): # pragma: no cover
102 raise Exception('Cant be executed on load phase')
103 dodo['task_zzz3'] = task_zzz3
104
105 # placeholder task is created with `loader` attribute
106 task_list = load_tasks(dodo, allow_delayed=True)
107 z_task = [t for t in task_list if t.name=='zzz3'][0]
108 assert z_task.loader.task_dep == 'yyy2'
109 assert z_task.loader.creator == task_zzz3
110
111 def testInitialLoadDelayedTask_no_delayed(self, dodo):
112 @create_after('yyy2')
113 def task_zzz3():
114 yield {'basename': 'foo', 'actions': None}
115 yield {'basename': 'bar', 'actions': None}
116 dodo['task_zzz3'] = task_zzz3
117
118 # load tasks as done by the `list` command
119 task_list = load_tasks(dodo, allow_delayed=False)
120 tasks = {t.name:t for t in task_list}
121 assert 'zzz3' not in tasks
122 assert tasks['foo'].loader is None
123 assert tasks['bar'].loader is None
124
125 def testInitialLoadDelayedTask_creates(self, dodo):
126 @create_after('yyy2', creates=['foo', 'bar'])
127 def task_zzz3(): # pragma: no cover
128 '''not loaded task doc'''
129 raise Exception('Cant be executed on load phase')
130 dodo['task_zzz3'] = task_zzz3
131
132 # placeholder task is created with `loader` attribute
133 task_list = load_tasks(dodo, allow_delayed=True)
134 tasks = {t.name:t for t in task_list}
135 assert 'zzz3' not in tasks
136 f_task = tasks['foo']
137 assert f_task.loader.task_dep == 'yyy2'
138 assert f_task.loader.creator == task_zzz3
139 assert tasks['bar'].loader.task_dep == tasks['foo'].loader.task_dep
140 assert tasks['foo'].doc == 'not loaded task doc'
141
142 # make sure doit can be executed more then once in single process GH#381
143 list2 = load_tasks(dodo, allow_delayed=True)
144 tasks2 = {t.name:t for t in list2}
145 assert tasks['bar'].loader is not tasks2['bar'].loader
146
147 def testCreateAfterDecoratorOnMethod(self):
148 'Check that class-defined tasks are loaded as bound methods'
149 class Tasks:
150 @create_after('yyy2')
151 def task_zzz3(): # pragma: no cover
152 pass
153
154 # create_after annotates the function
155 task_list = load_tasks({'task_zzz3': Tasks().task_zzz3}, allow_delayed=True)
156 tasks = {t.name:t for t in task_list}
157 task_zzz3 = tasks['zzz3']
158 assert isinstance(task_zzz3.loader, DelayedLoader)
159 # check creator is a bound method, not a plain function
160 assert getattr(task_zzz3.loader.creator, '__self__', None) is not None
161
162 def testCreateAfterDecoratorOnMethodWithParams(self, dodo):
163 'Check that class-defined tasks support the creates argument of @create_after'
164 class Tasks:
165 @create_after('yyy2', creates=['foo', 'bar'])
166 def task_zzz3(): # pragma: no cover
167 '''not loaded task doc'''
168 raise Exception('Cant be executed on load phase')
169
170 # placeholder task is created with `loader` attribute
171 task_list = load_tasks({'task_zzz3': Tasks().task_zzz3}, allow_delayed=True)
172 tasks = {t.name:t for t in task_list}
173 assert 'zzz3' not in tasks
174 f_task = tasks['foo']
175 assert f_task.loader.task_dep == 'yyy2'
176 assert getattr(f_task.loader.creator, '__self__', None) is not None
177 # loaders are not the same because of #381 (multiple execution on same process)
178 # But this is not a problem because once the task already exists, the loader is just not used.
179 # assert tasks['bar'].loader is tasks['foo'].loader
180 assert tasks['foo'].doc == 'not loaded task doc'
181
182 def testNameInBlacklist(self):
183 dodo_module = {'task_cmd_name': lambda:None}
184 pytest.raises(InvalidDodoFile, load_tasks, dodo_module, ['cmd_name'])
185
186 def testDocString(self, dodo):
187 task_list = load_tasks(dodo)
188 assert "task doc" == task_list[0].doc
189
190 def testMetaInfo(self, dodo):
191 task_list = load_tasks(dodo)
192 assert task_list[2].meta == {'a': ['b', 'c']}
193
194 def testUse_create_doit_tasks(self):
195 def original(): pass
196 def creator():
197 return {'actions': ['do nothing'], 'file_dep': ['foox']}
198 original.create_doit_tasks = creator
199 task_list = load_tasks({'x': original})
200 assert 1 == len(task_list)
201 assert set(['foox']) == task_list[0].file_dep
202
203 def testUse_create_doit_tasks_class_method(self):
204 class Foo(object):
205 def __init__(self):
206 self.create_doit_tasks = self._create_doit_tasks
207 def _create_doit_tasks(self):
208 return {'actions': ['do nothing'], 'file_dep': ['fooy']}
209
210 task_list = load_tasks({'Foo':Foo, 'foo':Foo()})
211 assert len(task_list) == 1
212 assert task_list[0].file_dep == set(['fooy'])
213
214 def testUse_create_doit_tasks_basename_kwargs(self):
215 class Foo(object):
216 def __init__(self):
217 @task_params([{"name": "t", "default": None, "type": list}])
218 def creator(**kwargs):
219 return self._create_doit_tasks(**kwargs)
220 creator.basename = 'my-foo'
221 self.create_doit_tasks = creator
222
223 def _create_doit_tasks(self, **kwargs):
224 return {'actions': ['do nothing'], 'file_dep': ['fooy'], 'targets': kwargs['t']}
225
226 task_list = load_tasks({'Foo':Foo, 'foo':Foo()}, task_opts={'my-foo': {'t': ['bar']}})
227 assert len(task_list) == 1
228 assert task_list[0].name == 'my-foo'
229 assert task_list[0].targets == ['bar']
230
231 def testUse_object_methods(self):
232 class Dodo(object):
233 def foo(self): # pragma: no cover
234 pass
235
236 def task_method1(self):
237 return {'actions':None}
238
239 def task_method2(self):
240 return {'actions':None}
241
242 methods = dict(inspect.getmembers(Dodo()))
243 task_list = load_tasks(methods)
244 assert 2 == len(task_list)
245 assert 'method1' == task_list[0].name
246 assert 'method2' == task_list[1].name
247
248
249
250 class TestTaskGeneratorParams(object):
251
252 def test_task_params_annotations(self):
253 params = [{"name": "foo", "default": "bar", "long": "foo"}]
254 func = task_params(params)(lambda: 1)
255 assert func._task_creator_params == params
256
257 def test_default(self):
258 'Ensure that a task parameter can be passed to the task generator.'
259
260 @task_params([{"name": "foo", "default": "bar", "long": "foo"}])
261 def task_foo(foo):
262 return {
263 'actions': [],
264 'doc': foo
265 }
266 task_list = load_tasks({'task_foo': task_foo})
267 task = task_list.pop()
268 assert task.doc == 'bar'
269 task.init_options()
270 assert task.options['foo'] == 'bar'
271
272 def test_args(self):
273 'Ensure that a task generator parameter can be set from the command line.'
274 @task_params([{"name": "fp", "default": "default p", "long": "fp"}])
275 def task_foo(fp):
276 return {
277 'actions': [],
278 'doc': fp
279 }
280 args = ['foo', '--fp=from_arg']
281 task_list = load_tasks({'task_foo': task_foo}, args=args)
282 task = task_list.pop()
283 assert task.doc == 'from_arg'
284
285
286 def test_call_api(self):
287 'Ensure that a task generator parameter can be set from direct API call'
288 @task_params([{"name": "fp", "default": "default p", "long": "fp"}])
289 def task_foo(fp):
290 return {
291 'actions': [],
292 'doc': fp
293 }
294 args = ['foo']
295 task_opts = {'foo': {'fp': 'from_api'}}
296 task_list = load_tasks({'task_foo': task_foo}, args=args, task_opts=task_opts)
297 task = task_list.pop()
298 assert task.doc == 'from_api'
299
300
301 def test_args_second(self):
302 def task_bar():
303 return {'actions': []}
304
305 @task_params([{"name": "foo", "default": "placeholder", "long": "foo"}])
306 def task_foo(foo):
307 return {
308 'actions': [],
309 'doc': foo
310 }
311 args = ['bar', 'foo', '--foo=from_arg']
312 task_list = load_tasks({'task_foo': task_foo, 'task_bar': task_bar}, args=args)
313 assert len(task_list) == 2
314 bar, foo = sorted(task_list, key=attrgetter('name'))
315 assert foo.name == 'foo'
316 assert foo.doc == 'from_arg'
317
318
319 def test_config(self):
320 @task_params([{"name": "fp", "default": "default p", "long": "fp"}])
321 def task_foo(fp):
322 return {
323 'actions': [],
324 'doc': fp
325 }
326 config = {'task:foo': {'fp': 'from_config'}}
327 task_list = load_tasks({'task_foo': task_foo}, args=(), config=config)
328 task = task_list.pop()
329 assert task.doc == 'from_config'
330 # config is overwritten from args
331 args = ['foo', '--fp=from_arg']
332 task_list2 = load_tasks({'task_foo': task_foo}, args=args, config=config)
333 task2 = task_list2.pop()
334 assert task2.doc == 'from_arg'
335
336
337 def test_method(self):
338 'Ensure that a task parameter can be passed to the task generator defined as a class method.'
339 class Tasks(object):
340 @task_params([{"name": "param1", "default": "placeholder", "long": "param1"}])
341 def task_foo(self, param1):
342 for i in range(2):
343 yield {
344 'name': 'subtask' + str(i),
345 'actions': [],
346 'doc': param1,
347 }
348
349 foo = Tasks().task_foo
350 task_list = load_tasks({'task_foo': foo}, args=('foo', '--param1=my_val'))
351
352 assert len(task_list) == 3
353 tasks = {t.name: t for t in task_list}
354
355 assert len(tasks['foo'].params) == 0
356 assert len(tasks['foo'].creator_params) == 1
357 assert tasks['foo'].doc == ''
358
359 assert len(tasks['foo:subtask0'].params) == 0
360 assert tasks['foo:subtask0'].doc == 'my_val'
361
362
363 def test_delayed(self):
364 @create_after()
365 @task_params([{"name": "fp", "default": "default p", "long": "fp"}])
366 def task_foo(fp):
367 return {
368 'actions': [],
369 'doc': fp
370 }
371 args = ['foo', '--fp=from_arg']
372 task_list = load_tasks({'task_foo': task_foo}, allow_delayed=True, args=args)
373 task = task_list.pop()
374 assert task.name == 'foo'
375 assert task.loader.kwargs == {'fp': 'from_arg'}
376 assert len(task.creator_params) == 1
377
378
379 def test_dup_param(self):
380 'Ensure that `params` field and @task_params definitions are prohibited'
381 @task_params([{"name": "foo", "default": "decorator", "long": "foo"}])
382 def task_dup(foo):
383 return {
384 'actions': [],
385 'params': [{"name": "bar", "default": "dict", "long": "bar"}],
386 }
387
388 with pytest.raises(InvalidTask) as exc_info:
389 load_tasks({'task_dup': task_dup})
390 assert ('attribute can not be used in conjuction with' in str(exc_info.value))
391
392
393
394
395 class TestDodoConfig(object):
396
397 def testConfigType_Error(self):
398 pytest.raises(InvalidDodoFile, load_doit_config, {'DOIT_CONFIG': 'abc'})
399
400 def testConfigDict_Ok(self,):
401 config = load_doit_config({'DOIT_CONFIG': {'verbose': 2}})
402 assert {'verbose': 2} == config
403
404 def testDefaultConfig_Dict(self):
405 config = load_doit_config({'whatever': 2})
406 assert {} == config
407
408
409
410 class TestGenerateTaskInvalid(object):
411 def testInvalidValue(self):
412 pytest.raises(InvalidTask, generate_tasks, "dict",'xpto 14')
413
414 class TestGenerateTaskNone(object):
415 def testEmpty(self):
416 tasks = generate_tasks('xx', None)
417 assert len(tasks) == 0
418
419
420 class TestGenerateTasksSingle(object):
421 def testDict(self):
422 tasks = generate_tasks("my_name", {'actions':['xpto 14']})
423 assert isinstance(tasks[0], Task)
424 assert "my_name" == tasks[0].name
425
426 def testTaskObj(self):
427 tasks = generate_tasks("foo", Task('bar', None))
428 assert 1 == len(tasks)
429 assert tasks[0].name == 'bar'
430
431 def testBaseName(self):
432 tasks = generate_tasks("function_name", {
433 'basename': 'real_task_name',
434 'actions':['xpto 14']
435 })
436 assert isinstance(tasks[0], Task)
437 assert "real_task_name" == tasks[0].name
438
439 # name field is only for subtasks.
440 def testInvalidNameField(self):
441 pytest.raises(InvalidTask, generate_tasks, "my_name",
442 {'actions':['xpto 14'],'name':'bla bla'})
443
444
445 def testUseDocstring(self):
446 tasks = generate_tasks("dict",{'actions':['xpto 14']}, "my doc")
447 assert "my doc" == tasks[0].doc
448
449 def testDocstringNotUsed(self):
450 mytask = {'actions':['xpto 14'], 'doc':'from dict'}
451 tasks = generate_tasks("dict", mytask, "from docstring")
452 assert "from dict" == tasks[0].doc
453
454
455 class TestGenerateTasksGenerator(object):
456
457 def testGenerator(self):
458 def f_xpto():
459 for i in range(3):
460 yield {'name':str(i), 'actions' :["xpto -%d"%i]}
461 tasks = generate_tasks("xpto", f_xpto())
462 assert isinstance(tasks[0], Task)
463 assert 4 == len(tasks)
464 assert tasks[0].subtask_of is None
465 assert "xpto:0" == tasks[0].task_dep[0]
466 assert "xpto:0" == tasks[1].name
467 assert tasks[1].subtask_of == 'xpto'
468
469 def testMultiLevelGenerator(self):
470 def f_xpto(base_name):
471 """second level docstring"""
472 for i in range(3):
473 name = "%s-%d" % (base_name, i)
474 yield {'name':name, 'actions' :["xpto -%d"%i]}
475 def f_first_level():
476 for i in range(2):
477 yield f_xpto(str(i))
478 tasks = generate_tasks("xpto", f_first_level())
479 assert isinstance(tasks[0], Task)
480 assert 7 == len(tasks)
481 assert tasks[0].subtask_of is None
482 assert f_xpto.__doc__ == tasks[0].doc
483 assert tasks[1].subtask_of == 'xpto'
484 assert "xpto:0-0" == tasks[1].name
485 assert "xpto:1-2" == tasks[-1].name
486
487
488 def testGeneratorReturnTaskObj(self):
489 def foo(base_name):
490 for i in range(3):
491 name = "%s-%d" % (base_name, i)
492 yield Task(name, actions=["xpto -%d"%i])
493 tasks = generate_tasks("foo", foo('bar'))
494 assert 3 == len(tasks)
495 assert tasks[0].name == 'bar-0'
496 assert tasks[1].name == 'bar-1'
497 assert tasks[2].name == 'bar-2'
498
499
500 def testGeneratorDoesntReturnDict(self):
501 def f_xpto():
502 for i in range(3):
503 yield "xpto -%d" % i
504 pytest.raises(InvalidTask, generate_tasks, "xpto", f_xpto())
505
506 def testGeneratorDictMissingAction(self):
507 def f_xpto():
508 for i in range(3):
509 yield {'name':str(i)}
510 pytest.raises(InvalidTask, generate_tasks, "xpto", f_xpto())
511
512
513 def testGeneratorDictMissingName(self):
514 def f_xpto():
515 for i in range(3):
516 yield {'actions' :["xpto -%d"%i]}
517 pytest.raises(InvalidTask, generate_tasks, "xpto", f_xpto())
518
519 def testGeneratorBasename(self):
520 def f_xpto():
521 for i in range(3):
522 yield {'basename':str(i), 'actions' :["xpto"]}
523 tasks = sorted(generate_tasks("xpto", f_xpto()), key=lambda t:t.name)
524 assert isinstance(tasks[0], Task)
525 assert 3 == len(tasks)
526 assert "0" == tasks[0].name
527 assert tasks[0].subtask_of is None
528 assert tasks[1].subtask_of is None
529
530 def testGeneratorBasenameName(self):
531 def f_xpto():
532 for i in range(3):
533 yield {'basename':'xpto', 'name':str(i), 'actions' :["a"]}
534 tasks = sorted(generate_tasks("f_xpto", f_xpto()))
535 assert isinstance(tasks[0], Task)
536 assert 4 == len(tasks)
537 assert "xpto" == tasks[0].name
538 assert "xpto:0" == tasks[1].name
539 assert tasks[0].subtask_of is None
540 assert tasks[1].subtask_of == 'xpto'
541
542 def testGeneratorBasenameCanNotRepeat(self):
543 def f_xpto():
544 for i in range(3):
545 yield {'basename':'again', 'actions' :["xpto"]}
546 pytest.raises(InvalidTask, generate_tasks, "xpto", f_xpto())
547
548 def testGeneratorBasenameCanNotRepeatNonGroup(self):
549 def f_xpto():
550 yield {'basename': 'xpto', 'actions':["a"]}
551 for i in range(3):
552 yield {'name': str(i),
553 'actions' :["a"]}
554 pytest.raises(InvalidTask, generate_tasks, "xpto", f_xpto())
555
556 def testGeneratorNameCanNotRepeat(self):
557 def f_xpto():
558 yield {'basename':'bn', 'name': 'xxx', 'actions' :["xpto"]}
559 yield {'basename':'bn', 'name': 'xxx', 'actions' :["xpto2"]}
560 pytest.raises(InvalidTask, generate_tasks, "xpto", f_xpto())
561
562 def testGeneratorDocString(self):
563 def f_xpto():
564 "the doc"
565 for i in range(3):
566 yield {'name':str(i), 'actions' :["xpto -%d"%i]}
567 tasks = sorted(generate_tasks("xpto", f_xpto(), f_xpto.__doc__))
568 assert "the doc" == tasks[0].doc
569
570 def testGeneratorWithNoTasks(self):
571 def f_xpto():
572 for x in []: yield x
573 tasks = generate_tasks("xpto", f_xpto())
574 assert 1 == len(tasks)
575 assert "xpto" == tasks[0].name
576 assert tasks[0].subtask_of is None
577
578
579 def testGeneratorBaseOnly(self):
580 def f_xpto():
581 yield {'basename':'xpto', 'name':None, 'doc': 'xxx doc'}
582 tasks = sorted(generate_tasks("f_xpto", f_xpto()))
583 assert 1 == len(tasks)
584 assert isinstance(tasks[0], Task)
585 assert "xpto" == tasks[0].name
586 assert tasks[0].has_subtask
587 assert 'xxx doc' == tasks[0].doc