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 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457
|
# coding=UTF-8
import os, shutil
import tempfile
import six
from six import StringIO
import pytest
from doit.exceptions import TaskError
from doit.exceptions import CatchedException
from doit import action
from doit import task
#path to test folder
TEST_PATH = os.path.dirname(__file__)
PROGRAM = "python %s/sample_process.py" % TEST_PATH
class TestTaskCheckInput(object):
def testOkType(self):
task.Task.check_attr('xxx', 'attr', [], ([int, list],[]))
def testOkValue(self):
task.Task.check_attr('xxx', 'attr', None, ([list], [None]))
def testFailType(self):
pytest.raises(task.InvalidTask, task.Task.check_attr, 'xxx',
'attr', int, ([list], [False]))
def testFailValue(self):
pytest.raises(task.InvalidTask, task.Task.check_attr, 'xxx',
'attr', True, ([list], [False]))
class TestTaskInit(object):
def test_groupTask(self):
# group tasks have no action
t = task.Task("taskX", None)
assert t.actions == []
def test_dependencySequenceIsValid(self):
task.Task("Task X", ["taskcmd"], file_dep=["123","456"])
# dependency must be a sequence or bool.
# give proper error message when anything else is used.
def test_dependencyNotSequence(self):
filePath = "data/dependency1"
pytest.raises(task.InvalidTask, task.Task,
"Task X",["taskcmd"], file_dep=filePath)
def test_options(self):
# when task is created, options contain the default values
p1 = {'name':'p1', 'default':'p1-default'}
p2 = {'name':'p2', 'default':'', 'short':'m'}
t = task.Task("MyName", None, params=[p1, p2])
assert 'p1-default' == t.options['p1']
assert '' == t.options['p2']
def test_setup(self):
t = task.Task("task5", ['action'], setup=["task2"])
assert ["task2"] == t.setup_tasks
class TestTaskValueSavers(object):
def test_execute_value_savers(self):
t = task.Task("Task X", ["taskcmd"])
t.value_savers.append(lambda: {'v1':1})
t.save_extra_values()
assert 1 == t.values['v1']
class TestTaskUpToDate(object):
def test_FalseRunalways(self):
t = task.Task("Task X", ["taskcmd"], uptodate=[False])
assert t.uptodate == [(False, None, None)]
def test_NoneIgnored(self):
t = task.Task("Task X", ["taskcmd"], uptodate=[None])
assert t.uptodate == [(None, None, None)]
def test_callable_function(self):
def custom_check(): return True
t = task.Task("Task X", ["taskcmd"], uptodate=[custom_check])
assert t.uptodate[0] == (custom_check, [], {})
def test_callable_instance_method(self):
class Base(object):
def check(): return True
base = Base()
t = task.Task("Task X", ["taskcmd"], uptodate=[base.check])
assert t.uptodate[0] == (base.check, [], {})
def test_tuple(self):
def custom_check(pos_arg, xxx=None): return True
t = task.Task("Task X", ["taskcmd"],
uptodate=[(custom_check, [123], {'xxx':'yyy'})])
assert t.uptodate[0] == (custom_check, [123], {'xxx':'yyy'})
def test_str(self):
t = task.Task("Task X", ["taskcmd"], uptodate=['my-cmd xxx'])
assert t.uptodate[0] == ('my-cmd xxx', [], {})
def test_object_with_configure(self):
class Check(object):
def __call__(self): return True
def configure_task(self, task):
task.task_dep.append('y1')
check = Check()
t = task.Task("Task X", ["taskcmd"], uptodate=[check])
assert (check, [], {}) == t.uptodate[0]
assert ['y1'] == t.task_dep
def test_invalid(self):
pytest.raises(task.InvalidTask,
task.Task, "Task X", ["taskcmd"], uptodate=[{'x':'y'}])
class TestTaskExpandFileDep(object):
def test_dependencyStringIsFile(self):
my_task = task.Task("Task X", ["taskcmd"], file_dep=["123","456"])
assert set(["123","456"]) == my_task.file_dep
def test_file_dep_must_be_string(self):
pytest.raises(task.InvalidTask, task.Task, "Task X", ["taskcmd"],
file_dep=[['aaaa']])
def test_file_dep_unicode(self):
unicode_name = six.u("中文")
my_task = task.Task("Task X", ["taskcmd"], file_dep=[unicode_name])
assert unicode_name in my_task.file_dep
class TestTaskDeps(object):
def test_task_dep(self):
my_task = task.Task("Task X", ["taskcmd"], task_dep=["123","4*56"])
assert ["123"] == my_task.task_dep
assert ["4*56"] == my_task.wild_dep
def test_calc_dep(self):
my_task = task.Task("Task X", ["taskcmd"], calc_dep=["123"])
assert set(["123"]) == my_task.calc_dep
def test_update_deps(self):
my_task = task.Task("Task X", ["taskcmd"], file_dep=["fileX"],
calc_dep=["calcX"], uptodate=[None])
my_task.update_deps({'file_dep': ['fileY'],
'task_dep': ['taskY'],
'calc_dep': ['calcX', 'calcY'],
'uptodate': [True],
'to_be_ignored': 'asdf',
})
assert set(['fileX', 'fileY']) == my_task.file_dep
assert ['taskY'] == my_task.task_dep
assert set(['calcX', 'calcY']) == my_task.calc_dep
assert [(None, None, None), (True, None, None)] == my_task.uptodate
class TestTask_Getargs(object):
def test_ok(self):
getargs = {'x' : ('t1','x'), 'y': ('t2','z')}
t = task.Task('t3', None, getargs=getargs)
assert 't1' in t.setup_tasks
assert 't2' in t.setup_tasks
def test_invalid_desc(self):
getargs = {'x' : 't1'}
assert pytest.raises(task.InvalidTask, task.Task,
't3', None, getargs=getargs)
def test_invalid_desc_tuple(self):
getargs = {'x' : ('t1',)}
assert pytest.raises(task.InvalidTask, task.Task,
't3', None, getargs=getargs)
class TestTaskTitle(object):
def test_title(self):
t = task.Task("MyName",["MyAction"])
assert "MyName" == t.title()
def test_custom_title(self):
t = task.Task("MyName",["MyAction"], title=(lambda x: "X%sX" % x.name))
assert "X%sX"%str(t.name) == t.title(), t.title()
class TestTaskRepr(object):
def test_repr(self):
t = task.Task("taskX",None,('t1','t2'))
assert "<Task: taskX>" == repr(t), repr(t)
class TestTaskActions(object):
def test_success(self):
t = task.Task("taskX", [PROGRAM])
t.execute()
def test_result(self):
# task.result is the value of last action
t = task.Task('t1', ["%s hi_list hi1" % PROGRAM,
"%s hi_list hi2" % PROGRAM])
t.execute()
assert "hi_listhi2" == t.result
def test_values(self):
def return_dict(d): return d
# task.result is the value of last action
t = task.Task('t1', [(return_dict, [{'x':5}]),
(return_dict, [{'y':10}]),])
t.execute()
assert {'x':5, 'y':10} == t.values
def test_failure(self):
t = task.Task("taskX", ["%s 1 2 3" % PROGRAM])
got = t.execute()
assert isinstance(got, TaskError)
# make sure all cmds are being executed.
def test_many(self):
t = task.Task("taskX",["%s hi_stdout hi2" % PROGRAM,
"%s hi_list hi6" % PROGRAM])
t.execute()
got = "".join([a.out for a in t.actions])
assert "hi_stdouthi_list" == got, repr(got)
def test_fail_first(self):
t = task.Task("taskX", ["%s 1 2 3" % PROGRAM, PROGRAM])
got = t.execute()
assert isinstance(got, TaskError)
def test_fail_second(self):
t = task.Task("taskX", ["%s 1 2" % PROGRAM, "%s 1 2 3" % PROGRAM])
got = t.execute()
assert isinstance(got, TaskError)
# python and commands mixed on same task
def test_mixed(self):
def my_print(msg):
import sys # python3 2to3 cant handle print with a trailing comma
sys.stdout.write(msg)
t = task.Task("taskX",["%s hi_stdout hi2" % PROGRAM,
(my_print,['_PY_']),
"%s hi_list hi6" % PROGRAM])
t.execute()
got = "".join([a.out for a in t.actions])
assert "hi_stdout_PY_hi_list" == got, repr(got)
class TestTaskTeardown(object):
def test_ok(self):
got = []
def put(x):
got.append(x)
t = task.Task('t1', [], teardown=[(put, [1]), (put, [2])])
assert None == t.execute_teardown()
assert [1,2] == got
def test_fail(self):
def my_raise():
raise Exception('hoho')
t = task.Task('t1', [], teardown=[(my_raise,)])
got = t.execute_teardown()
assert isinstance(got, CatchedException)
class TestTaskClean(object):
@pytest.fixture
def tmpdir(self, request):
tmpdir = {}
tmpdir['dir'] = tempfile.mkdtemp(prefix='doit-')
files = [os.path.join(tmpdir['dir'], fname)
for fname in ['a.txt', 'b.txt']]
tmpdir['files'] = files
# create empty files
for filename in tmpdir['files']:
open(filename, 'a').close()
def remove_tmpdir():
if os.path.exists(tmpdir['dir']):
shutil.rmtree(tmpdir['dir'])
request.addfinalizer(remove_tmpdir)
return tmpdir
def test_clean_nothing(self, tmpdir):
t = task.Task("xxx", None)
assert False == t._remove_targets
assert 0 == len(t.clean_actions)
t.clean(StringIO(), False)
for filename in tmpdir['files']:
assert os.path.exists(filename)
def test_clean_targets(self, tmpdir):
t = task.Task("xxx", None, targets=tmpdir['files'], clean=True)
assert True == t._remove_targets
assert 0 == len(t.clean_actions)
t.clean(StringIO(), False)
for filename in tmpdir['files']:
assert not os.path.exists(filename), filename
def test_clean_non_existent_targets(self):
t = task.Task('xxx', None, targets=["i_dont_exist"], clean=True)
t.clean(StringIO(), False)
# nothing is raised
def test_clean_empty_dirs(self, tmpdir):
# Remove empty directories listed in targets
targets = tmpdir['files'] + [tmpdir['dir']]
t = task.Task("xxx", None, targets=targets, clean=True)
assert True == t._remove_targets
assert 0 == len(t.clean_actions)
t.clean(StringIO(), False)
for filename in tmpdir['files']:
assert not os.path.exists(filename)
assert not os.path.exists(tmpdir['dir'])
def test_keep_non_empty_dirs(self, tmpdir):
# Keep non empty directories listed in targets
targets = [tmpdir['files'][0], tmpdir['dir']]
t = task.Task("xxx", None, targets=targets, clean=True)
assert True == t._remove_targets
assert 0 == len(t.clean_actions)
t.clean(StringIO(), False)
for filename in tmpdir['files']:
expected = not filename in targets
assert expected == os.path.exists(filename)
assert os.path.exists(tmpdir['dir'])
def test_clean_actions(self, tmpdir):
# a clean action can be anything, it can even not clean anything!
c_path = tmpdir['files'][0]
def say_hello():
fh = open(c_path, 'a')
fh.write("hello!!!")
fh.close()
t = task.Task("xxx",None,targets=tmpdir['files'], clean=[(say_hello,)])
assert False == t._remove_targets
assert 1 == len(t.clean_actions)
t.clean(StringIO(), False)
for filename in tmpdir['files']:
assert os.path.exists(filename)
fh = open(c_path, 'r')
got = fh.read()
fh.close()
assert "hello!!!" == got
def test_clean_action_error(self, capsys):
def fail_clean():
5/0
t = task.Task("xxx", None, clean=[(fail_clean,)])
assert 1 == len(t.clean_actions)
t.clean(StringIO(), dryrun=False)
err = capsys.readouterr()[1]
assert "PythonAction Error" in err
def test_clean_action_kwargs(self):
def fail_clean(dryrun):
six.print_('hello %s' % dryrun)
t = task.Task("xxx", None, clean=[(fail_clean,)])
assert 1 == len(t.clean_actions)
out = StringIO()
t.clean(out, dryrun=False)
assert "hello False" in out.getvalue()
def test_dryrun_file(self, tmpdir):
t = task.Task("xxx", None, targets=tmpdir['files'], clean=True)
assert True == t._remove_targets
assert 0 == len(t.clean_actions)
t.clean(StringIO(), True)
# files are NOT removed
for filename in tmpdir['files']:
assert os.path.exists(filename), filename
def test_dryrun_dir(self, tmpdir):
targets = tmpdir['files'] + [tmpdir['dir']]
for filename in tmpdir['files']:
os.remove(filename)
t = task.Task("xxx", None, targets=targets, clean=True)
assert True == t._remove_targets
assert 0 == len(t.clean_actions)
t.clean(StringIO(), True)
assert os.path.exists(tmpdir['dir'])
def test_dryrun_actions(self, tmpdir):
# a clean action can be anything, it can even not clean anything!
self.executed = False
def say_hello(): self.executed = True
t = task.Task("xxx",None,targets=tmpdir['files'], clean=[(say_hello,)])
assert False == t._remove_targets
assert 1 == len(t.clean_actions)
t.clean(StringIO(), True)
assert not self.executed
class TestTaskDoc(object):
def test_no_doc(self):
t = task.Task("name", ["action"])
assert '' == t.doc
def test_single_line(self):
t = task.Task("name", ["action"], doc=" i am doc")
assert "i am doc" == t.doc
def test_multiple_lines(self):
t = task.Task("name", ["action"], doc="i am doc \n with many lines\n")
assert "i am doc" == t.doc
def test_start_with_empty_lines(self):
t = task.Task("name", ["action"], doc="\n\n i am doc \n")
assert "i am doc" == t.doc
def test_just_new_line(self):
t = task.Task("name", ["action"], doc=" \n \n\n")
assert "" == t.doc
class TestTaskUpdateFromPickle(object):
def test_change_value(self):
t = task.Task("my_name", ["action"])
assert {} == t.values
class FakePickle():
def __init__(self):
self.values = [1,2,3]
t.update_from_pickle(FakePickle())
assert [1,2,3] == t.values
assert 'my_name' == t.name
class TestDictToTask(object):
def testDictOkMinimum(self):
dict_ = {'name':'simple','actions':['xpto 14']}
assert isinstance(task.dict_to_task(dict_), task.Task)
def testDictFieldTypo(self):
dict_ = {'name':'z','actions':['xpto 14'],'typo_here':['xxx']}
pytest.raises(action.InvalidTask, task.dict_to_task, dict_)
def testDictMissingFieldAction(self):
pytest.raises(action.InvalidTask, task.dict_to_task, {'name':'xpto 14'})
|