Debian Codegraph @

testing/mozharness/test/test_base_script.py

raw
1 import gc
2 import os
3 import re
4 import shutil
5 import tempfile
6 import types
7 import unittest
8 from unittest import mock
9
10 import mozunit
11
12 PYWIN32 = False
13 if os.name == "nt":
14 try:
15 import win32file
16
17 PYWIN32 = True
18 except ImportError:
19 pass
20
21
22 import mozharness.base.errors as errors
23 import mozharness.base.log as log
24 import mozharness.base.script as script
25 from mozharness.base.config import parse_config_file
26 from mozharness.base.log import CRITICAL, DEBUG, ERROR, FATAL, IGNORE, INFO, WARNING
27
28 here = os.path.dirname(os.path.abspath(__file__))
29
30 test_string = """foo
31 bar
32 baz"""
33
34
35 class CleanupObj(script.ScriptMixin, log.LogMixin):
36 def __init__(self):
37 super(CleanupObj, self).__init__()
38 self.log_obj = None
39 self.config = {"log_level": ERROR}
40
41
42 def cleanup(files=None):
43 files = files or []
44 files.extend(("test_logs", "test_dir", "tmpfile_stdout", "tmpfile_stderr"))
45 gc.collect()
46 c = CleanupObj()
47 for f in files:
48 c.rmtree(f)
49
50
51 def get_debug_script_obj():
52 s = script.BaseScript(
53 config={"log_type": "multi", "log_level": DEBUG},
54 initial_config_file="test/test.json",
55 )
56 return s
57
58
59 def _post_fatal(self, **kwargs):
60 fh = open("tmpfile_stdout", "w")
61 print(test_string, file=fh)
62 fh.close()
63
64
65 # TestScript {{{1
66 class TestScript(unittest.TestCase):
67 def setUp(self):
68 cleanup()
69 self.s = None
70 self.tmpdir = tempfile.mkdtemp(suffix=".mozharness")
71
72 def tearDown(self):
73 # Close the logfile handles, or windows can't remove the logs
74 if hasattr(self, "s") and isinstance(self.s, object):
75 del self.s
76 cleanup([self.tmpdir])
77
78 # test _dump_config_hierarchy() when --dump-config-hierarchy is passed
79 def test_dump_config_hierarchy_valid_files_len(self):
80 try:
81 self.s = script.BaseScript(
82 initial_config_file="test/test.json",
83 option_args=["--cfg", "test/test_override.py,test/test_override2.py"],
84 config={"dump_config_hierarchy": True},
85 )
86 except SystemExit:
87 local_cfg_files = parse_config_file("test_logs/localconfigfiles.json")
88 # first let's see if the correct number of config files were
89 # realized
90 self.assertEqual(
91 len(local_cfg_files),
92 4,
93 msg="--dump-config-hierarchy dumped wrong number of config files",
94 )
95
96 def test_dump_config_hierarchy_keys_unique_and_valid(self):
97 try:
98 self.s = script.BaseScript(
99 initial_config_file="test/test.json",
100 option_args=["--cfg", "test/test_override.py,test/test_override2.py"],
101 config={"dump_config_hierarchy": True},
102 )
103 except SystemExit:
104 local_cfg_files = parse_config_file("test_logs/localconfigfiles.json")
105 # now let's see if only unique items were added from each config
106 t_override = local_cfg_files.get("test/test_override.py", {})
107 self.assertTrue(
108 t_override.get("keep_string") == "don't change me"
109 and len(t_override.keys()) == 1,
110 msg="--dump-config-hierarchy dumped wrong keys/value for "
111 "`test/test_override.py`. There should only be one "
112 "item and it should be unique to all the other "
113 "items in test_log/localconfigfiles.json.",
114 )
115
116 def test_dump_config_hierarchy_matches_self_config(self):
117 try:
118 ######
119 # we need temp_cfg because self.s will be gcollected (NoneType) by
120 # the time we get to SystemExit exception
121 # temp_cfg will differ from self.s.config because of
122 # 'dump_config_hierarchy'. we have to make a deepcopy because
123 # config is a locked dict
124 temp_s = script.BaseScript(
125 initial_config_file="test/test.json",
126 option_args=["--cfg", "test/test_override.py,test/test_override2.py"],
127 )
128 from copy import deepcopy
129
130 temp_cfg = deepcopy(temp_s.config)
131 temp_cfg.update({"dump_config_hierarchy": True})
132 ######
133 self.s = script.BaseScript(
134 initial_config_file="test/test.json",
135 option_args=["--cfg", "test/test_override.py,test/test_override2.py"],
136 config={"dump_config_hierarchy": True},
137 )
138 except SystemExit:
139 local_cfg_files = parse_config_file("test_logs/localconfigfiles.json")
140 # finally let's just make sure that all the items added up, equals
141 # what we started with: self.config
142 target_cfg = {}
143 for cfg_file in local_cfg_files:
144 target_cfg.update(local_cfg_files[cfg_file])
145 self.assertEqual(
146 target_cfg,
147 temp_cfg,
148 msg="all of the items (combined) in each cfg file dumped via "
149 "--dump-config-hierarchy does not equal self.config ",
150 )
151
152 # test _dump_config() when --dump-config is passed
153 def test_dump_config_equals_self_config(self):
154 try:
155 ######
156 # we need temp_cfg because self.s will be gcollected (NoneType) by
157 # the time we get to SystemExit exception
158 # temp_cfg will differ from self.s.config because of
159 # 'dump_config_hierarchy'. we have to make a deepcopy because
160 # config is a locked dict
161 temp_s = script.BaseScript(
162 initial_config_file="test/test.json",
163 option_args=["--cfg", "test/test_override.py,test/test_override2.py"],
164 )
165 from copy import deepcopy
166
167 temp_cfg = deepcopy(temp_s.config)
168 temp_cfg.update({"dump_config": True})
169 ######
170 self.s = script.BaseScript(
171 initial_config_file="test/test.json",
172 option_args=["--cfg", "test/test_override.py,test/test_override2.py"],
173 config={"dump_config": True},
174 )
175 except SystemExit:
176 target_cfg = parse_config_file("test_logs/localconfig.json")
177 self.assertEqual(
178 target_cfg,
179 temp_cfg,
180 msg="all of the items (combined) in each cfg file dumped via "
181 "--dump-config does not equal self.config ",
182 )
183
184 def test_nonexistent_mkdir_p(self):
185 self.s = script.BaseScript(initial_config_file="test/test.json")
186 self.s.mkdir_p("test_dir/foo/bar/baz")
187 self.assertTrue(os.path.isdir("test_dir/foo/bar/baz"), msg="mkdir_p error")
188
189 def test_existing_mkdir_p(self):
190 self.s = script.BaseScript(initial_config_file="test/test.json")
191 os.makedirs("test_dir/foo/bar/baz")
192 self.s.mkdir_p("test_dir/foo/bar/baz")
193 self.assertTrue(
194 os.path.isdir("test_dir/foo/bar/baz"), msg="mkdir_p error when dir exists"
195 )
196
197 def test_chdir(self):
198 self.s = script.BaseScript(initial_config_file="test/test.json")
199 cwd = os.getcwd()
200 self.s.chdir("test_logs")
201 self.assertEqual(os.path.join(cwd, "test_logs"), os.getcwd(), msg="chdir error")
202 self.s.chdir(cwd)
203
204 def test_chdir_relative(self):
205 subdir = os.path.join(self.tmpdir, "subdir")
206 os.mkdir(subdir)
207 self.s = script.BaseScript(initial_config_file="test/test.json")
208 cwd = os.getcwd()
209 os.chdir(self.tmpdir)
210 try:
211 self.s.chdir("subdir")
212 self.assertEqual(subdir, os.getcwd(), msg="chdir relative error")
213 finally:
214 os.chdir(cwd)
215
216 def _test_log_helper(self, obj):
217 obj.debug("Testing DEBUG")
218 obj.warning("Testing WARNING")
219 obj.error("Testing ERROR")
220 obj.critical("Testing CRITICAL")
221 try:
222 obj.fatal("Testing FATAL")
223 except SystemExit:
224 pass
225 else:
226 self.assertTrue(False, msg="fatal() didn't SystemExit!")
227
228 def test_log(self):
229 self.s = get_debug_script_obj()
230 self.s.log_obj = None
231 self._test_log_helper(self.s)
232 del self.s
233 self.s = script.BaseScript(initial_config_file="test/test.json")
234 self._test_log_helper(self.s)
235
236 def test_run_nonexistent_command(self):
237 self.s = get_debug_script_obj()
238 self.s.run_command(
239 command="this_cmd_should_not_exist --help",
240 env={"GARBLE": "FARG"},
241 error_list=errors.PythonErrorList,
242 )
243 error_logsize = os.path.getsize("test_logs/test_info.log")
244 self.assertTrue(error_logsize > 0, msg="command not found error not hit")
245
246 def test_run_command_in_bad_dir(self):
247 self.s = get_debug_script_obj()
248 self.s.run_command(
249 command="ls",
250 cwd="/this_dir_should_not_exist",
251 error_list=errors.PythonErrorList,
252 )
253 error_logsize = os.path.getsize("test_logs/test_error.log")
254 self.assertTrue(error_logsize > 0, msg="bad dir error not hit")
255
256 def test_get_output_from_command_in_bad_dir(self):
257 self.s = get_debug_script_obj()
258 self.s.get_output_from_command(command="ls", cwd="/this_dir_should_not_exist")
259 error_logsize = os.path.getsize("test_logs/test_error.log")
260 self.assertTrue(error_logsize > 0, msg="bad dir error not hit")
261
262 def test_get_output_from_command_with_missing_file(self):
263 self.s = get_debug_script_obj()
264 self.s.get_output_from_command(command="ls /this_file_should_not_exist")
265 error_logsize = os.path.getsize("test_logs/test_error.log")
266 self.assertTrue(error_logsize > 0, msg="bad file error not hit")
267
268 def test_get_output_from_command_with_missing_file2(self):
269 self.s = get_debug_script_obj()
270 self.s.run_command(
271 command="cat mozharness/base/errors.py",
272 error_list=[
273 {"substr": "error", "level": ERROR},
274 {
275 "regex": re.compile(",$"),
276 "level": IGNORE,
277 },
278 {
279 "substr": "]$",
280 "level": WARNING,
281 },
282 ],
283 )
284 error_logsize = os.path.getsize("test_logs/test_error.log")
285 self.assertTrue(error_logsize > 0, msg="error list not working properly")
286
287 def test_download_unpack(self):
288 # NOTE: The action is called *download*, however, it can work for files in disk
289 self.s = get_debug_script_obj()
290
291 archives_path = os.path.join(here, "helper_files", "archives")
292
293 # Test basic decompression
294 for archive in (
295 "archive.tar",
296 "archive.tar.bz2",
297 "archive.tar.gz",
298 "archive.tar.xz",
299 "archive.zip",
300 ):
301 self.s.download_unpack(
302 url=os.path.join(archives_path, archive), extract_to=self.tmpdir
303 )
304 self.assertIn("script.sh", os.listdir(os.path.join(self.tmpdir, "bin")))
305 self.assertIn("lorem.txt", os.listdir(self.tmpdir))
306 shutil.rmtree(self.tmpdir)
307
308 # Test permissions for extracted entries from zip archive
309 self.s.download_unpack(
310 url=os.path.join(archives_path, "archive.zip"),
311 extract_to=self.tmpdir,
312 )
313 file_stats = os.stat(os.path.join(self.tmpdir, "bin", "script.sh"))
314 orig_fstats = os.stat(
315 os.path.join(archives_path, "reference", "bin", "script.sh")
316 )
317 self.assertEqual(file_stats.st_mode, orig_fstats.st_mode)
318 shutil.rmtree(self.tmpdir)
319
320 # Test unzip specific dirs only
321 self.s.download_unpack(
322 url=os.path.join(archives_path, "archive.zip"),
323 extract_to=self.tmpdir,
324 extract_dirs=["bin/*"],
325 )
326 self.assertIn("bin", os.listdir(self.tmpdir))
327 self.assertNotIn("lorem.txt", os.listdir(self.tmpdir))
328 shutil.rmtree(self.tmpdir)
329
330 # Test for invalid filenames (Windows only)
331 if PYWIN32:
332 with self.assertRaises(IOError):
333 self.s.download_unpack(
334 url=os.path.join(archives_path, "archive_invalid_filename.zip"),
335 extract_to=self.tmpdir,
336 )
337
338 for archive in (
339 "archive-setuid.tar",
340 "archive-escape.tar",
341 "archive-link.tar",
342 "archive-link-abs.tar",
343 "archive-double-link.tar",
344 ):
345 with self.assertRaises(Exception):
346 self.s.download_unpack(
347 url=os.path.join(archives_path, archive),
348 extract_to=self.tmpdir,
349 )
350
351 def test_unpack(self):
352 self.s = get_debug_script_obj()
353
354 archives_path = os.path.join(here, "helper_files", "archives")
355
356 # Test basic decompression
357 for archive in (
358 "archive.tar",
359 "archive.tar.bz2",
360 "archive.tar.gz",
361 "archive.tar.xz",
362 "archive.zip",
363 ):
364 self.s.unpack(os.path.join(archives_path, archive), self.tmpdir)
365 self.assertIn("script.sh", os.listdir(os.path.join(self.tmpdir, "bin")))
366 self.assertIn("lorem.txt", os.listdir(self.tmpdir))
367 shutil.rmtree(self.tmpdir)
368
369 # Test permissions for extracted entries from zip archive
370 self.s.unpack(os.path.join(archives_path, "archive.zip"), self.tmpdir)
371 file_stats = os.stat(os.path.join(self.tmpdir, "bin", "script.sh"))
372 orig_fstats = os.stat(
373 os.path.join(archives_path, "reference", "bin", "script.sh")
374 )
375 self.assertEqual(file_stats.st_mode, orig_fstats.st_mode)
376 shutil.rmtree(self.tmpdir)
377
378 # Test extract specific dirs only
379 self.s.unpack(
380 os.path.join(archives_path, "archive.zip"),
381 self.tmpdir,
382 extract_dirs=["bin/*"],
383 )
384 self.assertIn("bin", os.listdir(self.tmpdir))
385 self.assertNotIn("lorem.txt", os.listdir(self.tmpdir))
386 shutil.rmtree(self.tmpdir)
387
388 # Test for invalid filenames (Windows only)
389 if PYWIN32:
390 with self.assertRaises(IOError):
391 self.s.unpack(
392 os.path.join(archives_path, "archive_invalid_filename.zip"),
393 self.tmpdir,
394 )
395
396 for archive in (
397 "archive-setuid.tar",
398 "archive-escape.tar",
399 "archive-link.tar",
400 "archive-link-abs.tar",
401 "archive-double-link.tar",
402 ):
403 with self.assertRaises(Exception):
404 self.s.unpack(os.path.join(archives_path, archive), self.tmpdir)
405
406
407 # TestHelperFunctions {{{1
408 class TestHelperFunctions(unittest.TestCase):
409 temp_file = "test_dir/mozilla"
410
411 def setUp(self):
412 cleanup()
413 self.s = None
414
415 def tearDown(self):
416 # Close the logfile handles, or windows can't remove the logs
417 if hasattr(self, "s") and isinstance(self.s, object):
418 del self.s
419 cleanup()
420
421 def _create_temp_file(self, contents=test_string):
422 os.mkdir("test_dir")
423 fh = open(self.temp_file, "w+")
424 fh.write(contents)
425 fh.close
426
427 def test_mkdir_p(self):
428 self.s = script.BaseScript(initial_config_file="test/test.json")
429 self.s.mkdir_p("test_dir")
430 self.assertTrue(os.path.isdir("test_dir"), msg="mkdir_p error")
431
432 def test_get_output_from_command(self):
433 self._create_temp_file()
434 self.s = script.BaseScript(initial_config_file="test/test.json")
435 contents = self.s.get_output_from_command(
436 ["bash", "-c", "cat %s" % self.temp_file]
437 )
438 self.assertEqual(
439 test_string,
440 contents,
441 msg="get_output_from_command('cat file') differs from fh.write",
442 )
443
444 def test_run_command(self):
445 self._create_temp_file()
446 self.s = script.BaseScript(initial_config_file="test/test.json")
447 temp_file_name = os.path.basename(self.temp_file)
448 self.assertEqual(
449 self.s.run_command("cat %s" % temp_file_name, cwd="test_dir"),
450 0,
451 msg="run_command('cat file') did not exit 0",
452 )
453
454 def test_move1(self):
455 self._create_temp_file()
456 self.s = script.BaseScript(initial_config_file="test/test.json")
457 temp_file2 = "%s2" % self.temp_file
458 self.s.move(self.temp_file, temp_file2)
459 self.assertFalse(
460 os.path.exists(self.temp_file),
461 msg="%s still exists after move()" % self.temp_file,
462 )
463
464 def test_move2(self):
465 self._create_temp_file()
466 self.s = script.BaseScript(initial_config_file="test/test.json")
467 temp_file2 = "%s2" % self.temp_file
468 self.s.move(self.temp_file, temp_file2)
469 self.assertTrue(
470 os.path.exists(temp_file2), msg="%s doesn't exist after move()" % temp_file2
471 )
472
473 def test_copyfile(self):
474 self._create_temp_file()
475 self.s = script.BaseScript(initial_config_file="test/test.json")
476 temp_file2 = "%s2" % self.temp_file
477 self.s.copyfile(self.temp_file, temp_file2)
478 self.assertEqual(
479 os.path.getsize(self.temp_file),
480 os.path.getsize(temp_file2),
481 msg="%s and %s are different sizes after copyfile()"
482 % (self.temp_file, temp_file2),
483 )
484
485 def test_existing_rmtree(self):
486 self._create_temp_file()
487 self.s = script.BaseScript(initial_config_file="test/test.json")
488 self.s.mkdir_p("test_dir/foo/bar/baz")
489 self.s.rmtree("test_dir")
490 self.assertFalse(os.path.exists("test_dir"), msg="rmtree unsuccessful")
491
492 def test_nonexistent_rmtree(self):
493 self.s = script.BaseScript(initial_config_file="test/test.json")
494 status = self.s.rmtree("test_dir")
495 self.assertFalse(status, msg="nonexistent rmtree error")
496
497 @unittest.skipUnless(PYWIN32, "PyWin32 specific")
498 def test_long_dir_rmtree(self):
499 self.s = script.BaseScript(initial_config_file="test/test.json")
500 # create a very long path that the command-prompt cannot delete
501 # by using unicode format (max path length 32000)
502 path = "\\\\?\\%s\\test_dir" % os.getcwd()
503 win32file.CreateDirectoryExW(".", path)
504
505 for x in range(0, 20):
506 print("path=%s" % path)
507 path = path + "\\%sxxxxxxxxxxxxxxxxxxxx" % x
508 win32file.CreateDirectoryExW(".", path)
509 self.s.rmtree("test_dir")
510 self.assertFalse(os.path.exists("test_dir"), msg="rmtree unsuccessful")
511
512 @unittest.skipUnless(PYWIN32, "PyWin32 specific")
513 def test_chmod_rmtree(self):
514 self._create_temp_file()
515 win32file.SetFileAttributesW(self.temp_file, win32file.FILE_ATTRIBUTE_READONLY)
516 self.s = script.BaseScript(initial_config_file="test/test.json")
517 self.s.rmtree("test_dir")
518 self.assertFalse(os.path.exists("test_dir"), msg="rmtree unsuccessful")
519
520 @unittest.skipIf(os.name == "nt", "Not for Windows")
521 def test_chmod(self):
522 self._create_temp_file()
523 self.s = script.BaseScript(initial_config_file="test/test.json")
524 self.s.chmod(self.temp_file, 0o100700)
525 self.assertEqual(os.stat(self.temp_file)[0], 33216, msg="chmod unsuccessful")
526
527 def test_env_normal(self):
528 self.s = script.BaseScript(initial_config_file="test/test.json")
529 script_env = self.s.query_env()
530 self.assertEqual(
531 script_env,
532 os.environ,
533 msg="query_env() != env\n%s\n%s" % (script_env, os.environ),
534 )
535
536 def test_env_normal2(self):
537 self.s = script.BaseScript(initial_config_file="test/test.json")
538 self.s.query_env()
539 script_env = self.s.query_env()
540 self.assertEqual(
541 script_env,
542 os.environ,
543 msg="Second query_env() != env\n%s\n%s" % (script_env, os.environ),
544 )
545
546 def test_env_partial(self):
547 self.s = script.BaseScript(initial_config_file="test/test.json")
548 script_env = self.s.query_env(partial_env={"foo": "bar"})
549 self.assertTrue("foo" in script_env and script_env["foo"] == "bar")
550
551 def test_env_path(self):
552 self.s = script.BaseScript(initial_config_file="test/test.json")
553 partial_path = "yaddayadda:%(PATH)s"
554 full_path = partial_path % {"PATH": os.environ["PATH"]}
555 script_env = self.s.query_env(partial_env={"PATH": partial_path})
556 self.assertEqual(script_env["PATH"], full_path)
557
558 def test_query_exe(self):
559 self.s = script.BaseScript(
560 initial_config_file="test/test.json",
561 config={"exes": {"foo": "bar"}},
562 )
563 path = self.s.query_exe("foo")
564 self.assertEqual(path, "bar")
565
566 def test_query_exe_string_replacement(self):
567 self.s = script.BaseScript(
568 initial_config_file="test/test.json",
569 config={
570 "base_work_dir": "foo",
571 "work_dir": "bar",
572 "exes": {"foo": os.path.join("%(abs_work_dir)s", "baz")},
573 },
574 )
575 path = self.s.query_exe("foo")
576 self.assertEqual(path, os.path.join("foo", "bar", "baz"))
577
578 def test_read_from_file(self):
579 self._create_temp_file()
580 self.s = script.BaseScript(initial_config_file="test/test.json")
581 contents = self.s.read_from_file(self.temp_file)
582 self.assertEqual(contents, test_string)
583
584 def test_read_from_nonexistent_file(self):
585 self.s = script.BaseScript(initial_config_file="test/test.json")
586 contents = self.s.read_from_file("nonexistent_file!!!")
587 self.assertEqual(contents, None)
588
589
590 # TestScriptLogging {{{1
591 class TestScriptLogging(unittest.TestCase):
592 # I need a log watcher helper function, here and in test_log.
593 def setUp(self):
594 cleanup()
595 self.s = None
596
597 def tearDown(self):
598 # Close the logfile handles, or windows can't remove the logs
599 if hasattr(self, "s") and isinstance(self.s, object):
600 del self.s
601 cleanup()
602
603 def test_info_logsize(self):
604 self.s = script.BaseScript(
605 config={"log_type": "multi"}, initial_config_file="test/test.json"
606 )
607 info_logsize = os.path.getsize("test_logs/test_info.log")
608 self.assertTrue(info_logsize > 0, msg="initial info logfile missing/size 0")
609
610 def test_add_summary_info(self):
611 self.s = script.BaseScript(
612 config={"log_type": "multi"}, initial_config_file="test/test.json"
613 )
614 info_logsize = os.path.getsize("test_logs/test_info.log")
615 self.s.add_summary("one")
616 info_logsize2 = os.path.getsize("test_logs/test_info.log")
617 self.assertTrue(
618 info_logsize < info_logsize2, msg="add_summary() info not logged"
619 )
620
621 def test_add_summary_warning(self):
622 self.s = script.BaseScript(
623 config={"log_type": "multi"}, initial_config_file="test/test.json"
624 )
625 warning_logsize = os.path.getsize("test_logs/test_warning.log")
626 self.s.add_summary("two", level=WARNING)
627 warning_logsize2 = os.path.getsize("test_logs/test_warning.log")
628 self.assertTrue(
629 warning_logsize < warning_logsize2,
630 msg="add_summary(level=%s) not logged in warning log" % WARNING,
631 )
632
633 def test_summary(self):
634 self.s = script.BaseScript(
635 config={"log_type": "multi"}, initial_config_file="test/test.json"
636 )
637 self.s.add_summary("one")
638 self.s.add_summary("two", level=WARNING)
639 info_logsize = os.path.getsize("test_logs/test_info.log")
640 warning_logsize = os.path.getsize("test_logs/test_warning.log")
641 self.s.summary()
642 info_logsize2 = os.path.getsize("test_logs/test_info.log")
643 warning_logsize2 = os.path.getsize("test_logs/test_warning.log")
644 msg = ""
645 if info_logsize >= info_logsize2:
646 msg += "summary() didn't log to info!\n"
647 if warning_logsize >= warning_logsize2:
648 msg += "summary() didn't log to warning!\n"
649 self.assertEqual(msg, "", msg=msg)
650
651 def _test_log_level(self, log_level, log_level_file_list):
652 self.s = script.BaseScript(
653 config={"log_type": "multi"}, initial_config_file="test/test.json"
654 )
655 if log_level != FATAL:
656 self.s.log("testing", level=log_level)
657 else:
658 self.s._post_fatal = types.MethodType(_post_fatal, self.s)
659 try:
660 self.s.fatal("testing")
661 except SystemExit:
662 contents = None
663 if os.path.exists("tmpfile_stdout"):
664 fh = open("tmpfile_stdout")
665 contents = fh.read()
666 fh.close()
667 self.assertEqual(contents.rstrip(), test_string, "_post_fatal failed!")
668 del self.s
669 msg = ""
670 for level in log_level_file_list:
671 log_path = "test_logs/test_%s.log" % level
672 if not os.path.exists(log_path):
673 msg += "%s doesn't exist!\n" % log_path
674 else:
675 filesize = os.path.getsize(log_path)
676 if not filesize > 0:
677 msg += "%s is size 0!\n" % log_path
678 self.assertEqual(msg, "", msg=msg)
679
680 def test_debug(self):
681 self._test_log_level(DEBUG, [])
682
683 def test_ignore(self):
684 self._test_log_level(IGNORE, [])
685
686 def test_info(self):
687 self._test_log_level(INFO, [INFO])
688
689 def test_warning(self):
690 self._test_log_level(WARNING, [INFO, WARNING])
691
692 def test_error(self):
693 self._test_log_level(ERROR, [INFO, WARNING, ERROR])
694
695 def test_critical(self):
696 self._test_log_level(CRITICAL, [INFO, WARNING, ERROR, CRITICAL])
697
698 def test_fatal(self):
699 self._test_log_level(FATAL, [INFO, WARNING, ERROR, CRITICAL, FATAL])
700
701
702 # TestRetry {{{1
703 class NewError(Exception):
704 pass
705
706
707 class OtherError(Exception):
708 pass
709
710
711 class TestRetry(unittest.TestCase):
712 def setUp(self):
713 self.ATTEMPT_N = 1
714 self.s = script.BaseScript(initial_config_file="test/test.json")
715
716 def tearDown(self):
717 # Close the logfile handles, or windows can't remove the logs
718 if hasattr(self, "s") and isinstance(self.s, object):
719 del self.s
720 cleanup()
721
722 def _succeedOnSecondAttempt(self, foo=None, exception=Exception):
723 if self.ATTEMPT_N == 2:
724 self.ATTEMPT_N += 1
725 return
726 self.ATTEMPT_N += 1
727 raise exception("Fail")
728
729 def _raiseCustomException(self):
730 return self._succeedOnSecondAttempt(exception=NewError)
731
732 def _alwaysPass(self):
733 self.ATTEMPT_N += 1
734 return True
735
736 def _mirrorArgs(self, *args, **kwargs):
737 return args, kwargs
738
739 def _alwaysFail(self):
740 raise Exception("Fail")
741
742 def testRetrySucceed(self):
743 # Will raise if anything goes wrong
744 self.s.retry(self._succeedOnSecondAttempt, attempts=2, sleeptime=0)
745
746 def testRetryFailWithoutCatching(self):
747 self.assertRaises(
748 Exception, self.s.retry, self._alwaysFail, sleeptime=0, exceptions=()
749 )
750
751 def testRetryFailEnsureRaisesLastException(self):
752 self.assertRaises(
753 SystemExit, self.s.retry, self._alwaysFail, sleeptime=0, error_level=FATAL
754 )
755
756 def testRetrySelectiveExceptionSucceed(self):
757 self.s.retry(
758 self._raiseCustomException,
759 attempts=2,
760 sleeptime=0,
761 retry_exceptions=(NewError,),
762 )
763
764 def testRetrySelectiveExceptionFail(self):
765 self.assertRaises(
766 NewError,
767 self.s.retry,
768 self._raiseCustomException,
769 attempts=2,
770 sleeptime=0,
771 retry_exceptions=(OtherError,),
772 )
773
774 # TODO: figure out a way to test that the sleep actually happened
775 def testRetryWithSleep(self):
776 self.s.retry(self._succeedOnSecondAttempt, attempts=2, sleeptime=1)
777
778 def testRetryOnlyRunOnce(self):
779 """Tests that retry() doesn't call the action again after success"""
780 self.s.retry(self._alwaysPass, attempts=3, sleeptime=0)
781 # self.ATTEMPT_N gets increased regardless of pass/fail
782 self.assertEqual(2, self.ATTEMPT_N)
783
784 def testRetryReturns(self):
785 ret = self.s.retry(self._alwaysPass, sleeptime=0)
786 self.assertEqual(ret, True)
787
788 def testRetryCleanupIsCalled(self):
789 cleanup = mock.Mock()
790 self.s.retry(self._succeedOnSecondAttempt, cleanup=cleanup, sleeptime=0)
791 self.assertEqual(cleanup.call_count, 1)
792
793 def testRetryArgsPassed(self):
794 args = (1, "two", 3)
795 kwargs = dict(foo="a", bar=7)
796 ret = self.s.retry(
797 self._mirrorArgs, args=args, kwargs=kwargs.copy(), sleeptime=0
798 )
799 print(ret)
800 self.assertEqual(ret[0], args)
801 self.assertEqual(ret[1], kwargs)
802
803
804 class BaseScriptWithDecorators(script.BaseScript):
805 def __init__(self, *args, **kwargs):
806 super(BaseScriptWithDecorators, self).__init__(*args, **kwargs)
807
808 self.pre_run_1_args = []
809 self.raise_during_pre_run_1 = False
810 self.pre_action_1_args = []
811 self.raise_during_pre_action_1 = False
812 self.pre_action_2_args = []
813 self.pre_action_3_args = []
814 self.post_action_1_args = []
815 self.raise_during_post_action_1 = False
816 self.post_action_2_args = []
817 self.post_action_3_args = []
818 self.post_run_1_args = []
819 self.raise_during_post_run_1 = False
820 self.post_run_2_args = []
821 self.raise_during_build = False
822
823 @script.PreScriptRun
824 def pre_run_1(self, *args, **kwargs):
825 self.pre_run_1_args.append((args, kwargs))
826
827 if self.raise_during_pre_run_1:
828 raise Exception(self.raise_during_pre_run_1)
829
830 @script.PreScriptAction
831 def pre_action_1(self, *args, **kwargs):
832 self.pre_action_1_args.append((args, kwargs))
833
834 if self.raise_during_pre_action_1:
835 raise Exception(self.raise_during_pre_action_1)
836
837 @script.PreScriptAction
838 def pre_action_2(self, *args, **kwargs):
839 self.pre_action_2_args.append((args, kwargs))
840
841 @script.PreScriptAction("clobber")
842 def pre_action_3(self, *args, **kwargs):
843 self.pre_action_3_args.append((args, kwargs))
844
845 @script.PostScriptAction
846 def post_action_1(self, *args, **kwargs):
847 self.post_action_1_args.append((args, kwargs))
848
849 if self.raise_during_post_action_1:
850 raise Exception(self.raise_during_post_action_1)
851
852 @script.PostScriptAction
853 def post_action_2(self, *args, **kwargs):
854 self.post_action_2_args.append((args, kwargs))
855
856 @script.PostScriptAction("build")
857 def post_action_3(self, *args, **kwargs):
858 self.post_action_3_args.append((args, kwargs))
859
860 @script.PostScriptRun
861 def post_run_1(self, *args, **kwargs):
862 self.post_run_1_args.append((args, kwargs))
863
864 if self.raise_during_post_run_1:
865 raise Exception(self.raise_during_post_run_1)
866
867 @script.PostScriptRun
868 def post_run_2(self, *args, **kwargs):
869 self.post_run_2_args.append((args, kwargs))
870
871 def build(self):
872 if self.raise_during_build:
873 raise Exception(self.raise_during_build)
874
875
876 class TestScriptDecorators(unittest.TestCase):
877 def setUp(self):
878 cleanup()
879 self.s = None
880
881 def tearDown(self):
882 if hasattr(self, "s") and isinstance(self.s, object):
883 del self.s
884
885 cleanup()
886
887 def test_decorators_registered(self):
888 self.s = BaseScriptWithDecorators(initial_config_file="test/test.json")
889
890 self.assertEqual(len(self.s._listeners["pre_run"]), 1)
891 self.assertEqual(len(self.s._listeners["pre_action"]), 3)
892 self.assertEqual(len(self.s._listeners["post_action"]), 3)
893 self.assertEqual(len(self.s._listeners["post_run"]), 2)
894
895 def test_pre_post_fired(self):
896 self.s = BaseScriptWithDecorators(initial_config_file="test/test.json")
897 self.s.run()
898
899 self.assertEqual(len(self.s.pre_run_1_args), 1)
900 self.assertEqual(len(self.s.pre_action_1_args), 2)
901 self.assertEqual(len(self.s.pre_action_2_args), 2)
902 self.assertEqual(len(self.s.pre_action_3_args), 1)
903 self.assertEqual(len(self.s.post_action_1_args), 2)
904 self.assertEqual(len(self.s.post_action_2_args), 2)
905 self.assertEqual(len(self.s.post_action_3_args), 1)
906 self.assertEqual(len(self.s.post_run_1_args), 1)
907
908 self.assertEqual(self.s.pre_run_1_args[0], ((), {}))
909
910 self.assertEqual(self.s.pre_action_1_args[0], (("clobber",), {}))
911 self.assertEqual(self.s.pre_action_1_args[1], (("build",), {}))
912
913 # pre_action_3 should only get called for the action it is registered
914 # with.
915 self.assertEqual(self.s.pre_action_3_args[0], (("clobber",), {}))
916
917 self.assertEqual(self.s.post_action_1_args[0][0], ("clobber",))
918 self.assertEqual(self.s.post_action_1_args[0][1], dict(success=True))
919 self.assertEqual(self.s.post_action_1_args[1][0], ("build",))
920 self.assertEqual(self.s.post_action_1_args[1][1], dict(success=True))
921
922 # post_action_3 should only get called for the action it is registered
923 # with.
924 self.assertEqual(self.s.post_action_3_args[0], (("build",), dict(success=True)))
925
926 self.assertEqual(self.s.post_run_1_args[0], ((), {}))
927
928 def test_post_always_fired(self):
929 self.s = BaseScriptWithDecorators(initial_config_file="test/test.json")
930 self.s.raise_during_build = "Testing post always fired."
931
932 with self.assertRaises(SystemExit):
933 self.s.run()
934
935 self.assertEqual(len(self.s.pre_run_1_args), 1)
936 self.assertEqual(len(self.s.pre_action_1_args), 2)
937 self.assertEqual(len(self.s.post_action_1_args), 2)
938 self.assertEqual(len(self.s.post_action_2_args), 2)
939 self.assertEqual(len(self.s.post_run_1_args), 1)
940 self.assertEqual(len(self.s.post_run_2_args), 1)
941
942 self.assertEqual(self.s.post_action_1_args[0][1], dict(success=True))
943 self.assertEqual(self.s.post_action_1_args[1][1], dict(success=False))
944 self.assertEqual(self.s.post_action_2_args[1][1], dict(success=False))
945
946 def test_pre_run_exception(self):
947 self.s = BaseScriptWithDecorators(initial_config_file="test/test.json")
948 self.s.raise_during_pre_run_1 = "Error during pre run 1"
949
950 with self.assertRaises(SystemExit):
951 self.s.run()
952
953 self.assertEqual(len(self.s.pre_run_1_args), 1)
954 self.assertEqual(len(self.s.pre_action_1_args), 0)
955 self.assertEqual(len(self.s.post_run_1_args), 1)
956 self.assertEqual(len(self.s.post_run_2_args), 1)
957
958 def test_pre_action_exception(self):
959 self.s = BaseScriptWithDecorators(initial_config_file="test/test.json")
960 self.s.raise_during_pre_action_1 = "Error during pre 1"
961
962 with self.assertRaises(SystemExit):
963 self.s.run()
964
965 self.assertEqual(len(self.s.pre_run_1_args), 1)
966 self.assertEqual(len(self.s.pre_action_1_args), 1)
967 self.assertEqual(len(self.s.pre_action_2_args), 0)
968 self.assertEqual(len(self.s.post_action_1_args), 1)
969 self.assertEqual(len(self.s.post_action_2_args), 1)
970 self.assertEqual(len(self.s.post_run_1_args), 1)
971 self.assertEqual(len(self.s.post_run_2_args), 1)
972
973 def test_post_action_exception(self):
974 self.s = BaseScriptWithDecorators(initial_config_file="test/test.json")
975 self.s.raise_during_post_action_1 = "Error during post 1"
976
977 with self.assertRaises(SystemExit):
978 self.s.run()
979
980 self.assertEqual(len(self.s.pre_run_1_args), 1)
981 self.assertEqual(len(self.s.post_action_1_args), 1)
982 self.assertEqual(len(self.s.post_action_2_args), 1)
983 self.assertEqual(len(self.s.post_run_1_args), 1)
984 self.assertEqual(len(self.s.post_run_2_args), 1)
985
986 def test_post_run_exception(self):
987 self.s = BaseScriptWithDecorators(initial_config_file="test/test.json")
988 self.s.raise_during_post_run_1 = "Error during post run 1"
989
990 with self.assertRaises(SystemExit):
991 self.s.run()
992
993 self.assertEqual(len(self.s.post_run_1_args), 1)
994 self.assertEqual(len(self.s.post_run_2_args), 1)
995
996
997 # main {{{1
998 if __name__ == "__main__":
999 mozunit.main()