3 # Copyright (C) 2010-2012 CEA/DEN
5 # This library is free software; you can redistribute it and/or
6 # modify it under the terms of the GNU Lesser General Public
7 # License as published by the Free Software Foundation; either
8 # version 2.1 of the License.
10 # This library is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 # Lesser General Public License for more details.
15 # You should have received a copy of the GNU Lesser General Public
16 # License along with this library; if not, write to the Free Software
17 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
27 from hashlib import sha1
29 from sha import sha as sha1
32 import src.ElementTree as etree
33 from src.xmlManager import add_simple_node
35 # Define all possible option for the test command : sat test <options>
36 parser = src.options.Options()
37 parser.add_option('b', 'base', 'string', 'base',
38 _("Optional: Indicate the name of the test base to use.\n\tThis name has to"
39 " be registered in your application and in a project.\n\tA path to a "
40 "test base can also be used."))
41 parser.add_option('l', 'launcher', 'string', 'launcher',
42 _("Optional: Use this option to specify the path to a SALOME launcher to "
43 "use to launch the test scripts of the test base."))
44 parser.add_option('g', 'grid', 'list', 'grids',
45 _('Optional: Indicate which grid(s) to test (subdirectory of the test '
47 parser.add_option('s', 'session', 'list', 'sessions',
48 _('Optional: indicate which session(s) to test (subdirectory of the '
50 parser.add_option('', 'display', 'string', 'display',
51 _("Optional: set the display where to launch SALOME.\n"
52 "\tIf value is NO then option --show-desktop=0 will be used to launch SALOME."))
55 '''method that is called when salomeTools is called with --help option.
57 :return: The text to display for the test command description.
60 return _("The test command runs a test base on a SALOME installation.\n\n"
61 "example:\nsat test SALOME-master --grid GEOM --session light")
63 def parse_option(args, config):
64 """ Parse the options and do some verifications about it
66 :param args List: The list of arguments of the command
67 :param config Config: The global configuration
68 :return: the options of the current command launch and the full arguments
69 :rtype: Tuple (options, args)
71 (options, args) = parser.parse_args(args)
73 if not options.launcher:
75 elif not os.path.isabs(options.launcher):
76 if not src.config_has_application(config):
77 raise src.SatException(_("An application is required to use a "
78 "relative path with option --appli"))
79 options.launcher = os.path.join(config.APPLICATION.workdir,
82 if not os.path.exists(options.launcher):
83 raise src.SatException(_("Launcher not found: %s") %
86 return (options, args)
91 path = raw_input("enter a path where to save the result: ")
93 result = raw_input("the result will be not save. Are you sure to "
100 elif os.path.exists(path):
101 result = raw_input("Warning, the content of %s will be deleted. Are you"
102 " sure to continue ? [y/n] " % path)
110 def save_file(filename, base):
111 f = open(filename, 'r')
115 objectname = sha1(content).hexdigest()
117 f = gzip.open(os.path.join(base, '.objects', objectname), 'w')
122 def move_test_results(in_dir, what, out_dir, logger):
123 if out_dir == in_dir:
130 # create test results directory if necessary
131 #logger.write("FINAL = %s\n" % finalPath, 5)
132 if not os.access(finalPath, os.F_OK):
133 #shutil.rmtree(finalPath)
134 os.makedirs(finalPath)
137 logger.error(_("%s cannot be created.") % finalPath)
138 finalPath = ask_a_path()
141 os.makedirs(os.path.join(finalPath, what, 'BASES'))
143 # check if .objects directory exists
144 if not os.access(os.path.join(finalPath, '.objects'), os.F_OK):
145 os.makedirs(os.path.join(finalPath, '.objects'))
147 logger.write(_('copy tests results to %s ... ') % finalPath, 3)
149 #logger.write("\n", 5)
152 shutil.copy2(os.path.join(in_dir, what, 'env_info.py'),
153 os.path.join(finalPath, what, 'env_info.py'))
155 # for all sub directory (ie testbase) in the BASES directory
156 for testbase in os.listdir(os.path.join(in_dir, what, 'BASES')):
157 outtestbase = os.path.join(finalPath, what, 'BASES', testbase)
158 intestbase = os.path.join(in_dir, what, 'BASES', testbase)
160 # ignore files in root dir
161 if not os.path.isdir(intestbase):
164 os.makedirs(outtestbase)
165 #logger.write(" copy testbase %s\n" % testbase, 5)
167 for grid_ in [m for m in os.listdir(intestbase) if os.path.isdir(
168 os.path.join(intestbase, m))]:
169 # ignore source configuration directories
170 if grid_[:4] == '.git' or grid_ == 'CVS':
173 outgrid = os.path.join(outtestbase, grid_)
174 ingrid = os.path.join(intestbase, grid_)
176 #logger.write(" copy grid %s\n" % grid_, 5)
178 if grid_ == 'RESSOURCES':
179 for file_name in os.listdir(ingrid):
180 if not os.path.isfile(os.path.join(ingrid,
183 f = open(os.path.join(outgrid, file_name), "w")
184 f.write(save_file(os.path.join(ingrid, file_name),
188 for session_name in [t for t in os.listdir(ingrid) if
189 os.path.isdir(os.path.join(ingrid, t))]:
190 outsession = os.path.join(outgrid, session_name)
191 insession = os.path.join(ingrid, session_name)
192 os.makedirs(outsession)
194 for file_name in os.listdir(insession):
195 if not os.path.isfile(os.path.join(insession,
198 if file_name.endswith('result.py'):
199 shutil.copy2(os.path.join(insession, file_name),
200 os.path.join(outsession, file_name))
202 f = open(os.path.join(outsession, file_name), "w")
203 f.write(save_file(os.path.join(insession,
208 logger.write(src.printcolors.printc("OK"), 3, False)
209 logger.write("\n", 3, False)
211 def check_remote_machine(machine_name, logger):
212 logger.write(_("\ncheck the display on %s\n" % machine_name), 4)
213 ssh_cmd = 'ssh -o "StrictHostKeyChecking no" %s "ls"' % machine_name
214 logger.write(_("Executing the command : %s " % ssh_cmd), 4)
215 p = subprocess.Popen(ssh_cmd,
217 stdin =subprocess.PIPE,
218 stdout=subprocess.PIPE,
219 stderr=subprocess.PIPE)
221 if p.returncode != 0:
222 logger.write(src.printcolors.printc(src.KO_STATUS) + "\n", 1)
223 logger.write(" " + src.printcolors.printcError(p.stderr.read()), 2)
224 logger.write(src.printcolors.printcWarning((
225 "No ssh access to the display machine.")),1)
227 logger.write(src.printcolors.printcSuccess(src.OK_STATUS) + "\n\n", 4)
230 # Creates the XML report for a product.
231 def create_test_report(config,
236 # get the date and hour of the launching of the command, in order to keep
238 date_hour = config.VARS.datehour
240 # Get some information to put in the xml file
241 application_name = config.VARS.application
242 withappli = src.config_has_application(config)
245 if not os.path.exists(xml_history_path):
247 root = etree.Element("salome")
248 prod_node = etree.Element("product", name=application_name, build=xmlname)
249 root.append(prod_node)
251 root = etree.parse(xml_history_path).getroot()
252 prod_node = root.find("product")
254 prod_node.attrib["history_file"] = os.path.basename(xml_history_path)
255 prod_node.attrib["global_res"] = retcode
259 for node in (prod_node.findall("version_to_download") +
260 prod_node.findall("out_dir")):
261 prod_node.remove(node)
263 add_simple_node(prod_node, "version_to_download",
264 config.APPLICATION.name)
266 add_simple_node(prod_node, "out_dir", config.APPLICATION.workdir)
270 for node in prod_node.findall("exec"):
271 prod_node.remove(node)
273 exec_node = add_simple_node(prod_node, "exec")
274 exec_node.append(etree.Element("env", name="Host", value=config.VARS.node))
275 exec_node.append(etree.Element("env", name="Architecture",
276 value=config.VARS.dist))
277 exec_node.append(etree.Element("env", name="Number of processors",
278 value=str(config.VARS.nb_proc)))
279 exec_node.append(etree.Element("env", name="Begin date",
280 value=src.parse_date(date_hour)))
281 exec_node.append(etree.Element("env", name="Command",
282 value=config.VARS.command))
283 exec_node.append(etree.Element("env", name="sat version",
284 value=config.INTERNAL.sat_version))
286 if 'TESTS' in config:
288 tests = add_simple_node(prod_node, "tests")
289 known_errors = add_simple_node(prod_node, "known_errors")
290 new_errors = add_simple_node(prod_node, "new_errors")
291 amend = add_simple_node(prod_node, "amend")
293 tests = prod_node.find("tests")
294 known_errors = prod_node.find("known_errors")
295 new_errors = prod_node.find("new_errors")
296 amend = prod_node.find("amend")
299 for test in config.TESTS:
300 if not tt.has_key(test.testbase):
301 tt[test.testbase] = [test]
303 tt[test.testbase].append(test)
305 for testbase in tt.keys():
307 gn = add_simple_node(tests, "testbase")
309 gn = tests.find("testbase")
310 # initialize all grids and session to "not executed"
311 for mn in gn.findall("grid"):
312 mn.attrib["executed_last_time"] = "no"
313 for tyn in mn.findall("session"):
314 tyn.attrib["executed_last_time"] = "no"
315 for test_node in tyn.findall('test'):
316 for node in test_node.getchildren():
317 if node.tag != "history":
318 test_node.remove(node)
321 for attribute in test_node.attrib:
322 if (attribute != "script" and
324 attribs_to_pop.append(attribute)
325 for attribute in attribs_to_pop:
326 test_node.attrib.pop(attribute)
328 gn.attrib['name'] = testbase
329 nb, nb_pass, nb_failed, nb_timeout, nb_not_run = 0, 0, 0, 0, 0
332 for test in tt[testbase]:
333 if not grids.has_key(test.grid):
335 mn = add_simple_node(gn, "grid")
336 mn.attrib['name'] = test.grid
338 l_mn = gn.findall("grid")
340 for grid_node in l_mn:
341 if grid_node.attrib['name'] == test.grid:
345 mn = add_simple_node(gn, "grid")
346 mn.attrib['name'] = test.grid
348 grids[test.grid] = mn
350 mn.attrib["executed_last_time"] = "yes"
352 if not sessions.has_key("%s/%s" % (test.grid, test.session)):
354 tyn = add_simple_node(mn, "session")
355 tyn.attrib['name'] = test.session
357 l_tyn = mn.findall("session")
359 for session_node in l_tyn:
360 if session_node.attrib['name'] == test.session:
364 tyn = add_simple_node(mn, "session")
365 tyn.attrib['name'] = test.session
367 sessions["%s/%s" % (test.grid, test.session)] = tyn
369 tyn.attrib["executed_last_time"] = "yes"
371 for script in test.script:
373 tn = add_simple_node(sessions[
374 "%s/%s" % (test.grid, test.session)],
376 tn.attrib['session'] = test.session
377 tn.attrib['script'] = script.name
378 hn = add_simple_node(tn, "history")
380 l_tn = sessions["%s/%s" % (test.grid, test.session)].findall(
383 for test_node in l_tn:
384 if test_node.attrib['script'] == script['name']:
389 tn = add_simple_node(sessions[
390 "%s/%s" % (test.grid, test.session)],
392 tn.attrib['session'] = test.session
393 tn.attrib['script'] = script.name
394 hn = add_simple_node(tn, "history")
396 # Get or create the history node for the current test
397 if len(tn.findall("history")) == 0:
398 hn = add_simple_node(tn, "history")
400 hn = tn.find("history")
401 # Put the last test data into the history
402 if 'res' in tn.attrib:
403 attributes = {"date_hour" : date_hour,
404 "res" : tn.attrib['res'] }
409 if node.tag != "history":
412 if 'callback' in script:
414 cnode = add_simple_node(tn, "callback")
415 if src.architecture.is_windows():
418 lambda x: x in string.printable,
421 cnode.text = script.callback.decode(
423 except UnicodeDecodeError as exc:
424 zz = (script.callback[:exc.start] +
426 script.callback[exc.end-2:])
427 cnode = add_simple_node(tn, "callback")
428 cnode.text = zz.decode("UTF-8")
430 # Add the script content
431 cnode = add_simple_node(tn, "content")
432 cnode.text = script.content
434 # Add the script execution log
435 cnode = add_simple_node(tn, "out")
436 cnode.text = script.out
438 if 'amend' in script:
439 cnode = add_simple_node(tn, "amend")
440 cnode.text = script.amend.decode("UTF-8")
443 tn.attrib['exec_time'] = "?"
445 tn.attrib['exec_time'] = "%.3f" % script.time
446 tn.attrib['res'] = script.res
448 if "amend" in script:
449 amend_test = add_simple_node(amend, "atest")
450 amend_test.attrib['name'] = os.path.join(test.grid,
453 amend_test.attrib['reason'] = script.amend.decode(
458 if script.res == src.OK_STATUS: nb_pass += 1
459 elif script.res == src.TIMEOUT_STATUS: nb_timeout += 1
460 elif script.res == src.KO_STATUS: nb_failed += 1
461 else: nb_not_run += 1
463 if "known_error" in script:
464 kf_script = add_simple_node(known_errors, "error")
465 kf_script.attrib['name'] = os.path.join(test.grid,
468 kf_script.attrib['date'] = script.known_error.date
470 'expected'] = script.known_error.expected
472 'comment'] = script.known_error.comment.decode("UTF-8")
473 kf_script.attrib['fixed'] = str(
474 script.known_error.fixed)
475 overdue = datetime.datetime.today().strftime("%Y-%m-"
476 "%d") > script.known_error.expected
478 kf_script.attrib['overdue'] = str(overdue)
480 elif script.res == src.KO_STATUS:
481 new_err = add_simple_node(new_errors, "new_error")
482 script_path = os.path.join(test.grid,
483 test.session, script.name)
484 new_err.attrib['name'] = script_path
485 new_err.attrib['cmd'] = ("sat testerror %s -s %s -c 'my"
486 " comment' -p %s" % \
487 (application_name, script_path, config.VARS.dist))
490 gn.attrib['total'] = str(nb)
491 gn.attrib['pass'] = str(nb_pass)
492 gn.attrib['failed'] = str(nb_failed)
493 gn.attrib['timeout'] = str(nb_timeout)
494 gn.attrib['not_run'] = str(nb_not_run)
496 # Remove the res attribute of all tests that were not launched
498 for mn in gn.findall("grid"):
499 if mn.attrib["executed_last_time"] == "no":
500 for tyn in mn.findall("session"):
501 if tyn.attrib["executed_last_time"] == "no":
502 for test_node in tyn.findall('test'):
503 if "res" in test_node.attrib:
504 test_node.attrib.pop("res")
506 if len(xmlname) == 0:
507 xmlname = application_name
508 if not xmlname.endswith(".xml"):
511 src.xmlManager.write_report(os.path.join(dest_path, xmlname),
514 src.xmlManager.write_report(xml_history_path,
519 def generate_history_xml_path(config, test_base):
520 """Generate the name of the xml file that contain the history of the tests
521 on the machine with the current APPLICATION and the current test base.
523 :param config Config: The global configuration
524 :param test_base Str: The test base name (or path)
525 :return: the full path of the history xml file
528 history_xml_name = ""
529 if "APPLICATION" in config:
530 history_xml_name += config.APPLICATION.name
531 history_xml_name += "-"
532 history_xml_name += config.VARS.dist
533 history_xml_name += "-"
534 test_base_name = test_base
535 if os.path.exists(test_base):
536 test_base_name = os.path.basename(test_base)
537 history_xml_name += test_base_name
538 history_xml_name += ".xml"
539 return os.path.join(config.USER.log_dir, "TEST", history_xml_name)
541 def run(args, runner, logger):
542 '''method that is called when salomeTools is called with test parameter.
544 (options, args) = parse_option(args, runner.cfg)
546 with_application = False
547 if runner.cfg.VARS.application != 'None':
548 logger.write(_('Running tests on application %s\n') %
549 src.printcolors.printcLabel(
550 runner.cfg.VARS.application), 1)
551 with_application = True
552 elif not options.base:
553 raise src.SatException(_('A test base is required. Use the --base '
557 # check if environment is loaded
558 if 'KERNEL_ROOT_DIR' in os.environ:
559 logger.write(src.printcolors.printcWarning(_("WARNING: "
560 "SALOME environment already sourced")) + "\n", 1)
563 elif options.launcher:
564 logger.write(src.printcolors.printcWarning(_("Running SALOME "
565 "application.")) + "\n\n", 1)
567 msg = _("Impossible to find any launcher.\nPlease specify an "
568 "application or a launcher")
569 logger.write(src.printcolors.printcError(msg))
574 show_desktop = (options.display and options.display.upper() == "NO")
575 if options.display and options.display != "NO":
576 remote_name = options.display.split(':')[0]
577 if remote_name != "":
578 check_remote_machine(remote_name, logger)
579 # if explicitly set use user choice
580 os.environ['DISPLAY'] = options.display
581 elif 'DISPLAY' not in os.environ:
583 if ('display' in runner.cfg.SITE.test and
584 len(runner.cfg.SITE.test.display) > 0):
585 # use default value for test tool
586 os.environ['DISPLAY'] = runner.cfg.SITE.test.display
588 os.environ['DISPLAY'] = "localhost:0.0"
593 tmp_dir = runner.cfg.SITE.test.tmp_dir_with_application
595 tmp_dir = runner.cfg.SITE.test.tmp_dir
597 # remove previous tmp dir
598 if os.access(tmp_dir, os.F_OK):
600 shutil.rmtree(tmp_dir)
602 logger.error(_("error removing TT_TMP_RESULT %s\n")
606 lines.append("date = '%s'" % runner.cfg.VARS.date)
607 lines.append("hour = '%s'" % runner.cfg.VARS.hour)
608 lines.append("node = '%s'" % runner.cfg.VARS.node)
609 lines.append("arch = '%s'" % runner.cfg.VARS.dist)
611 if 'APPLICATION' in runner.cfg:
612 lines.append("application_info = {}")
613 lines.append("application_info['name'] = '%s'" %
614 runner.cfg.APPLICATION.name)
615 lines.append("application_info['tag'] = '%s'" %
616 runner.cfg.APPLICATION.tag)
617 lines.append("application_info['products'] = %s" %
618 str(runner.cfg.APPLICATION.products))
620 content = "\n".join(lines)
622 # create hash from context information
623 dirname = sha1(content.encode()).hexdigest()
624 base_dir = os.path.join(tmp_dir, dirname)
625 os.makedirs(base_dir)
626 os.environ['TT_TMP_RESULT'] = base_dir
628 # create env_info file
629 f = open(os.path.join(base_dir, 'env_info.py'), "w")
633 # create working dir and bases dir
634 working_dir = os.path.join(base_dir, 'WORK')
635 os.makedirs(working_dir)
636 os.makedirs(os.path.join(base_dir, 'BASES'))
637 os.chdir(working_dir)
639 if 'PYTHONPATH' not in os.environ:
640 os.environ['PYTHONPATH'] = ''
642 for var in os.environ['PYTHONPATH'].split(':'):
643 if var not in sys.path:
646 # launch of the tests
647 #####################
650 test_base = options.base
651 elif with_application and "test_base" in runner.cfg.APPLICATION:
652 test_base = runner.cfg.APPLICATION.test_base.name
654 src.printcolors.print_value(logger, _('Display'), os.environ['DISPLAY'], 2)
655 src.printcolors.print_value(logger, _('Timeout'),
656 runner.cfg.SITE.test.timeout, 2)
657 src.printcolors.print_value(logger, _("Working dir"), base_dir, 3)
659 # create the test object
660 test_runner = src.test_module.Test(runner.cfg,
665 sessions=options.sessions,
666 launcher=options.launcher,
667 show_desktop=show_desktop)
669 if not test_runner.test_base_found:
674 logger.allowPrintLevel = False
675 retcode = test_runner.run_all_tests()
676 logger.allowPrintLevel = True
678 logger.write(_("Tests finished"), 1)
679 logger.write("\n", 2, False)
681 logger.write(_("\nGenerate the specific test log\n"), 5)
682 out_dir = os.path.join(runner.cfg.USER.log_dir, "TEST")
683 src.ensure_path_exists(out_dir)
684 name_xml_board = logger.logFileName.split(".")[0] + "board" + ".xml"
685 historic_xml_path = generate_history_xml_path(runner.cfg, test_base)
687 create_test_report(runner.cfg,
691 xmlname = name_xml_board)
692 xml_board_path = os.path.join(out_dir, name_xml_board)
693 logger.l_logFiles.append(xml_board_path)
694 logger.add_link(os.path.join("TEST", name_xml_board),
697 "Click on the link to get the detailed test results")
699 # Add the historic files into the log files list of the command
700 logger.l_logFiles.append(historic_xml_path)
702 logger.write(_("Removing the temporary directory: "
703 "rm -rf %s\n" % test_runner.tmp_working_dir), 5)
704 if os.path.exists(test_runner.tmp_working_dir):
705 shutil.rmtree(test_runner.tmp_working_dir)