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
29 from hashlib import sha1
31 from sha import sha as sha1
34 import src.ElementTree as etree
35 from src.xmlManager import add_simple_node
37 # Define all possible option for the test command : sat test <options>
38 parser = src.options.Options()
39 parser.add_option('b', 'base', 'string', 'base',
40 _("""Optional: The name of the test base to use."
41 This name has to be registered in your application and in a project.
42 A path to a test base can also be used."""))
43 parser.add_option('l', 'launcher', 'string', 'launcher',
44 _("""Optional: Specify the path to a SALOME launcher
45 used to launch the test scripts of the test base."""))
46 parser.add_option('g', 'grid', 'list', 'grids',
47 _('Optional: Which grid(s) to test (subdirectory of the test base).'))
48 parser.add_option('s', 'session', 'list2', 'sessions',
49 _('Optional: Which session(s) to test (subdirectory of the grid).'))
50 parser.add_option('', 'display', 'string', 'display',
51 _("""Optional: Set the display where to launch SALOME.
52 If value is NO then option --show-desktop=0 will be used to launch SALOME."""))
53 parser.add_option('', 'keep', 'boolean', 'keeptempdir',
54 _('Optional: keep temporary big tests directories.'))
56 '''method that is called when salomeTools is called with --help option.
58 :return: The text to display for the test command description.
61 return _("The test command runs a test base on a SALOME installation.\n\n"
62 "example:\nsat test SALOME-master --grid GEOM --session light")
64 def parse_option_old(args, config):
65 """ Parse the options and do some verifications about it
67 :param args List: The list of arguments of the command
68 :param config Config: The global configuration
69 :return: the options of the current command launch and the full arguments
70 :rtype: Tuple (options, args)
72 (options, args) = parser.parse_args(args)
74 if not options.launcher:
76 elif not os.path.isabs(options.launcher):
77 if not src.config_has_application(config):
78 msg = _("An application is required to use a relative path with option --appli")
79 raise src.SatException(msg)
80 options.launcher = os.path.join(config.APPLICATION.workdir,
83 if not os.path.exists(options.launcher):
84 raise src.SatException(_("Launcher not found: %s") %
87 return (options, args)
90 def parse_option(args, config):
91 """ Parse the options and do some verifications about it
93 :param args List: The list of arguments of the command
94 :param config Config: The global configuration
95 :return: the options of the current command launch and the full arguments
96 :rtype: Tuple (options, args)
98 (options, args) = parser.parse_args(args)
100 if not options.launcher:
101 options.launcher = ""
102 return (options, args)
104 if not os.path.isabs(options.launcher):
105 if not src.config_has_application(config):
106 msg = _("An application is required to use a relative path with option --appli")
107 raise src.SatException(msg)
109 options.launcher = os.path.join(config.APPLICATION.workdir, options.launcher)
110 if not os.path.exists(options.launcher):
111 raise src.SatException(_("Launcher not found: %s") % options.launcher)
114 launcher = os.path.realpath(os.path.expandvars(options.launcher))
115 if os.path.exists(launcher):
116 options.launcher = launcher
117 return (options, args)
119 raise src.SatException(_("Launcher not found: %s") % options.launcher)
125 path = raw_input("enter a path where to save the result: ")
127 result = raw_input("the result will be not save. Are you sure to "
134 elif os.path.exists(path):
135 result = raw_input("Warning, the content of %s will be deleted. Are you"
136 " sure to continue ? [y/n] " % path)
144 def save_file(filename, base):
145 f = open(filename, 'r')
149 objectname = sha1(content).hexdigest()
151 f = gzip.open(os.path.join(base, '.objects', objectname), 'w')
156 def move_test_results(in_dir, what, out_dir, logger):
157 if out_dir == in_dir:
164 # create test results directory if necessary
165 #logger.write("FINAL = %s\n" % finalPath, 5)
166 if not os.access(finalPath, os.F_OK):
167 #shutil.rmtree(finalPath)
168 os.makedirs(finalPath)
171 logger.error(_("%s cannot be created.") % finalPath)
172 finalPath = ask_a_path()
175 os.makedirs(os.path.join(finalPath, what, 'BASES'))
177 # check if .objects directory exists
178 if not os.access(os.path.join(finalPath, '.objects'), os.F_OK):
179 os.makedirs(os.path.join(finalPath, '.objects'))
181 logger.write(_('copy tests results to %s ... ') % finalPath, 3)
183 #logger.write("\n", 5)
186 shutil.copy2(os.path.join(in_dir, what, 'env_info.py'),
187 os.path.join(finalPath, what, 'env_info.py'))
189 # for all sub directory (ie testbase) in the BASES directory
190 for testbase in os.listdir(os.path.join(in_dir, what, 'BASES')):
191 outtestbase = os.path.join(finalPath, what, 'BASES', testbase)
192 intestbase = os.path.join(in_dir, what, 'BASES', testbase)
194 # ignore files in root dir
195 if not os.path.isdir(intestbase):
198 os.makedirs(outtestbase)
199 #logger.write(" copy testbase %s\n" % testbase, 5)
201 for grid_ in [m for m in os.listdir(intestbase) \
202 if os.path.isdir(os.path.join(intestbase, m))]:
203 # ignore source configuration directories
204 if grid_[:4] == '.git' or grid_ == 'CVS':
207 outgrid = os.path.join(outtestbase, grid_)
208 ingrid = os.path.join(intestbase, grid_)
210 #logger.write(" copy grid %s\n" % grid_, 5)
212 if grid_ == 'RESSOURCES':
213 for file_name in os.listdir(ingrid):
214 if not os.path.isfile(os.path.join(ingrid,
217 f = open(os.path.join(outgrid, file_name), "w")
218 f.write(save_file(os.path.join(ingrid, file_name),
222 for session_name in [t for t in os.listdir(ingrid) if
223 os.path.isdir(os.path.join(ingrid, t))]:
224 outsession = os.path.join(outgrid, session_name)
225 insession = os.path.join(ingrid, session_name)
226 os.makedirs(outsession)
228 for file_name in os.listdir(insession):
229 if not os.path.isfile(os.path.join(insession,
232 if file_name.endswith('result.py'):
233 shutil.copy2(os.path.join(insession, file_name),
234 os.path.join(outsession, file_name))
236 f = open(os.path.join(outsession, file_name), "w")
237 f.write(save_file(os.path.join(insession,
242 logger.write(src.printcolors.printc("OK"), 3, False)
243 logger.write("\n", 3, False)
245 def check_remote_machine(machine_name, logger):
246 logger.write(_("\ncheck the display on %s\n" % machine_name), 4)
247 ssh_cmd = 'ssh -o "StrictHostKeyChecking no" %s "ls"' % machine_name
248 logger.write(_("Executing the command : %s " % ssh_cmd), 4)
249 p = subprocess.Popen(ssh_cmd,
251 stdin =subprocess.PIPE,
252 stdout=subprocess.PIPE,
253 stderr=subprocess.PIPE)
255 if p.returncode != 0:
256 logger.write(src.printcolors.printc(src.KO_STATUS) + "\n", 1)
257 logger.write(" " + src.printcolors.printcError(p.stderr.read()), 2)
258 logger.write(src.printcolors.printcWarning((
259 "No ssh access to the display machine.")),1)
261 logger.write(src.printcolors.printcSuccess(src.OK_STATUS) + "\n\n", 4)
263 def findOrCreateNode(parentNode, nameNodeToFind):
264 found = parentNode.find(nameNodeToFind)
266 created = add_simple_node(parentNode, nameNodeToFind)
272 # Creates the XML report for a product.
273 def create_test_report(config,
278 # get the date and hour of the launching of the command, in order to keep
280 date_hour = config.VARS.datehour
282 # Get some information to put in the xml file
283 application_name = config.VARS.application
284 withappli = src.config_has_application(config)
287 if not os.path.exists(xml_history_path):
288 print("Log file creation %s" % xml_history_path)
290 root = etree.Element("salome")
291 prod_node = etree.Element("product", name=application_name, build=xmlname)
292 root.append(prod_node)
294 print("Log file modification %s" % xml_history_path)
295 root = etree.parse(xml_history_path).getroot()
296 prod_node = root.find("product")
299 prod_node.attrib["history_file"] = os.path.basename(xml_history_path)
300 prod_node.attrib["global_res"] = retcode
304 for node in (prod_node.findall("version_to_download") +
305 prod_node.findall("out_dir")):
306 prod_node.remove(node)
308 add_simple_node(prod_node, "version_to_download", config.APPLICATION.name)
309 add_simple_node(prod_node, "out_dir", config.APPLICATION.workdir)
313 for node in prod_node.findall("exec"):
314 prod_node.remove(node)
316 exec_node = add_simple_node(prod_node, "exec")
317 exec_node.append(etree.Element("env", name="Host", value=config.VARS.node))
318 exec_node.append(etree.Element("env", name="Architecture", value=config.VARS.dist))
319 exec_node.append(etree.Element("env", name="Number of processors", value=str(config.VARS.nb_proc)))
320 exec_node.append(etree.Element("env", name="Begin date", value=src.parse_date(date_hour)))
321 exec_node.append(etree.Element("env", name="Command", value=config.VARS.command))
322 exec_node.append(etree.Element("env", name="sat version", value=config.INTERNAL.sat_version))
324 if 'TESTS' in config:
325 tests = findOrCreateNode(prod_node, "tests")
326 known_errors = findOrCreateNode(prod_node, "known_errors")
327 new_errors = findOrCreateNode(prod_node, "new_errors")
328 amend = findOrCreateNode(prod_node, "amend")
331 for test in config.TESTS:
332 if not test.testbase in tt:
333 tt[test.testbase] = [test]
335 tt[test.testbase].append(test)
337 for testbase in tt.keys():
338 if verbose: print("---- create_test_report %s %s" % (testbase, first_time))
339 gn = findOrCreateNode(tests, "testbase")
341 # initialize all grids and session to "not executed"
342 for mn in gn.findall("grid"):
343 mn.attrib["executed_last_time"] = "no"
344 for tyn in mn.findall("session"):
345 tyn.attrib["executed_last_time"] = "no"
346 for test_node in tyn.findall('test'):
347 for node in test_node.getchildren():
348 if node.tag != "history":
349 test_node.remove(node)
352 for attribute in test_node.attrib:
353 if (attribute != "script" and
355 attribs_to_pop.append(attribute)
356 for attribute in attribs_to_pop:
357 test_node.attrib.pop(attribute)
359 gn.attrib['name'] = testbase
360 nb, nb_pass, nb_failed, nb_timeout, nb_not_run = 0, 0, 0, 0, 0
363 for test in tt[testbase]:
364 if not grids.has_key(test.grid):
366 mn = add_simple_node(gn, "grid")
367 mn.attrib['name'] = test.grid
369 l_mn = gn.findall("grid")
371 for grid_node in l_mn:
372 if grid_node.attrib['name'] == test.grid:
376 mn = add_simple_node(gn, "grid")
377 mn.attrib['name'] = test.grid
379 grids[test.grid] = mn
381 mn.attrib["executed_last_time"] = "yes"
383 if not "%s/%s" % (test.grid, test.session) in sessions:
385 tyn = add_simple_node(mn, "session")
386 tyn.attrib['name'] = test.session
388 l_tyn = mn.findall("session")
390 for session_node in l_tyn:
391 if session_node.attrib['name'] == test.session:
395 tyn = add_simple_node(mn, "session")
396 tyn.attrib['name'] = test.session
398 sessions["%s/%s" % (test.grid, test.session)] = tyn
400 tyn.attrib["executed_last_time"] = "yes"
402 for script in test.script:
404 tn = add_simple_node(sessions[
405 "%s/%s" % (test.grid, test.session)],
407 tn.attrib['session'] = test.session
408 tn.attrib['script'] = script.name
409 hn = add_simple_node(tn, "history")
411 l_tn = sessions["%s/%s" % (test.grid, test.session)].findall(
414 for test_node in l_tn:
415 if test_node.attrib['script'] == script['name']:
420 tn = add_simple_node(sessions[
421 "%s/%s" % (test.grid, test.session)],
423 tn.attrib['session'] = test.session
424 tn.attrib['script'] = script.name
425 hn = add_simple_node(tn, "history")
427 # Get or create the history node for the current test
428 if len(tn.findall("history")) == 0:
429 hn = add_simple_node(tn, "history")
431 hn = tn.find("history")
432 # Put the last test data into the history
433 if 'res' in tn.attrib:
434 attributes = {"date_hour" : date_hour,
435 "res" : tn.attrib['res'] }
440 if node.tag != "history":
443 if 'callback' in script:
445 cnode = add_simple_node(tn, "callback")
446 if src.architecture.is_windows():
449 lambda x: x in string.printable,
452 cnode.text = script.callback.decode(
454 except UnicodeDecodeError as exc:
455 zz = (script.callback[:exc.start] +
457 script.callback[exc.end-2:])
458 cnode = add_simple_node(tn, "callback")
459 cnode.text = zz.decode("UTF-8")
461 # Add the script content
462 cnode = add_simple_node(tn, "content")
463 cnode.text = script.content
465 # Add the script execution log
466 cnode = add_simple_node(tn, "out")
467 cnode.text = script.out
469 if 'amend' in script:
470 cnode = add_simple_node(tn, "amend")
471 cnode.text = script.amend.decode("UTF-8")
474 tn.attrib['exec_time'] = "?"
476 tn.attrib['exec_time'] = "%.3f" % script.time
477 tn.attrib['res'] = script.res
479 if "amend" in script:
480 amend_test = add_simple_node(amend, "atest")
481 amend_test.attrib['name'] = os.path.join(test.grid,
484 amend_test.attrib['reason'] = script.amend.decode(
489 if script.res == src.OK_STATUS: nb_pass += 1
490 elif script.res == src.TIMEOUT_STATUS: nb_timeout += 1
491 elif script.res == src.KO_STATUS: nb_failed += 1
492 else: nb_not_run += 1
494 if "known_error" in script:
495 kf_script = add_simple_node(known_errors, "error")
496 kf_script.attrib['name'] = os.path.join(test.grid,
499 kf_script.attrib['date'] = script.known_error.date
501 'expected'] = script.known_error.expected
503 'comment'] = script.known_error.comment.decode("UTF-8")
504 kf_script.attrib['fixed'] = str(
505 script.known_error.fixed)
506 overdue = datetime.datetime.today().strftime("%Y-%m-"
507 "%d") > script.known_error.expected
509 kf_script.attrib['overdue'] = str(overdue)
511 elif script.res == src.KO_STATUS:
512 new_err = add_simple_node(new_errors, "new_error")
513 script_path = os.path.join(test.grid,
514 test.session, script.name)
515 new_err.attrib['name'] = script_path
516 new_err.attrib['cmd'] = ("sat testerror %s -s %s -c 'my"
517 " comment' -p %s" % \
518 (application_name, script_path, config.VARS.dist))
521 gn.attrib['total'] = str(nb)
522 gn.attrib['pass'] = str(nb_pass)
523 gn.attrib['failed'] = str(nb_failed)
524 gn.attrib['timeout'] = str(nb_timeout)
525 gn.attrib['not_run'] = str(nb_not_run)
527 # Remove the res attribute of all tests that were not launched
529 for mn in gn.findall("grid"):
530 if mn.attrib["executed_last_time"] == "no":
531 for tyn in mn.findall("session"):
532 if tyn.attrib["executed_last_time"] == "no":
533 for test_node in tyn.findall('test'):
534 if "res" in test_node.attrib:
535 test_node.attrib.pop("res")
537 if len(xmlname) == 0:
538 xmlname = application_name
539 if not xmlname.endswith(".xml"):
542 src.xmlManager.write_report(os.path.join(dest_path, xmlname), root, "test.xsl")
543 src.xmlManager.write_report(xml_history_path, root, "test_history.xsl")
546 def generate_history_xml_path(config, test_base):
547 """Generate the name of the xml file that contain the history of the tests
548 on the machine with the current APPLICATION and the current test base.
550 :param config Config: The global configuration
551 :param test_base Str: The test base name (or path)
552 :return: the full path of the history xml file
555 history_xml_name = ""
556 if "APPLICATION" in config:
557 history_xml_name += config.APPLICATION.name
558 history_xml_name += "-"
559 history_xml_name += config.VARS.dist
560 history_xml_name += "-"
561 test_base_name = test_base
562 if os.path.exists(test_base):
563 test_base_name = os.path.basename(test_base)
564 history_xml_name += test_base_name
565 history_xml_name += ".xml"
566 log_dir = src.get_log_path(config)
567 return os.path.join(log_dir, "TEST", history_xml_name)
569 def run(args, runner, logger):
570 '''method that is called when salomeTools is called with test parameter.
572 (options, args) = parse_option(args, runner.cfg)
574 # the test base is specified either by the application, or by the --base option
575 with_application = False
576 if runner.cfg.VARS.application != 'None':
577 logger.write(_('Running tests on application %s\n') %
578 src.printcolors.printcLabel(
579 runner.cfg.VARS.application), 1)
580 with_application = True
581 elif not options.base:
582 raise src.SatException(_('A test base is required. Use the --base '
585 # the launcher is specified either by the application, or by the --launcher option
587 # check if environment is loaded
588 if 'KERNEL_ROOT_DIR' in os.environ:
589 logger.write(src.printcolors.printcWarning(_("WARNING: "
590 "SALOME environment already sourced")) + "\n", 1)
593 elif options.launcher:
594 logger.write(src.printcolors.printcWarning(_("Running SALOME "
595 "application.")) + "\n\n", 1)
597 msg = _("Impossible to find any launcher.\nPlease specify an "
598 "application or a launcher")
599 logger.write(src.printcolors.printcError(msg))
604 show_desktop = (options.display and options.display.upper() == "NO")
605 if options.display and options.display != "NO":
606 remote_name = options.display.split(':')[0]
607 if remote_name != "":
608 check_remote_machine(remote_name, logger)
609 # if explicitly set use user choice
610 os.environ['DISPLAY'] = options.display
611 elif 'DISPLAY' not in os.environ:
613 if ('test' in runner.cfg.LOCAL and
614 'display' in runner.cfg.LOCAL.test and
615 len(runner.cfg.LOCAL.test.display) > 0):
616 # use default value for test tool
617 os.environ['DISPLAY'] = runner.cfg.LOCAL.test.display
619 os.environ['DISPLAY'] = "localhost:0.0"
624 tmp_dir = os.path.join(runner.cfg.VARS.tmp_root,
625 runner.cfg.APPLICATION.name,
628 tmp_dir = os.path.join(runner.cfg.VARS.tmp_root,
631 # remove previous tmp dir
632 if os.access(tmp_dir, os.F_OK):
634 shutil.rmtree(tmp_dir)
636 logger.error(_("error removing TT_TMP_RESULT %s\n")
640 lines.append("date = '%s'" % runner.cfg.VARS.date)
641 lines.append("hour = '%s'" % runner.cfg.VARS.hour)
642 lines.append("node = '%s'" % runner.cfg.VARS.node)
643 lines.append("arch = '%s'" % runner.cfg.VARS.dist)
645 if 'APPLICATION' in runner.cfg:
646 lines.append("application_info = {}")
647 lines.append("application_info['name'] = '%s'" %
648 runner.cfg.APPLICATION.name)
649 lines.append("application_info['tag'] = '%s'" %
650 runner.cfg.APPLICATION.tag)
651 lines.append("application_info['products'] = %s" %
652 str(runner.cfg.APPLICATION.products))
654 content = "\n".join(lines)
656 # create hash from context information
657 # CVW TODO or not dirname = datetime.datetime.now().strftime("%y%m%d_%H%M%S_") + sha1(content.encode()).hexdigest()[0:8]
658 dirname = sha1(content.encode()).hexdigest()[0:8] # only 8 firsts probably good
659 base_dir = os.path.join(tmp_dir, dirname)
660 os.makedirs(base_dir)
661 os.environ['TT_TMP_RESULT'] = base_dir
663 # create env_info file
664 with open(os.path.join(base_dir, 'env_info.py'), "w") as f:
667 # create working dir and bases dir
668 working_dir = os.path.join(base_dir, 'WORK')
669 os.makedirs(working_dir)
670 os.makedirs(os.path.join(base_dir, 'BASES'))
671 os.chdir(working_dir)
673 if 'PYTHONPATH' not in os.environ:
674 os.environ['PYTHONPATH'] = ''
676 for var in os.environ['PYTHONPATH'].split(':'):
677 if var not in sys.path:
680 # launch of the tests
681 #####################
684 test_base = options.base
685 elif with_application and "test_base" in runner.cfg.APPLICATION:
686 test_base = runner.cfg.APPLICATION.test_base.name
688 src.printcolors.print_value(logger, _('Display'), os.environ['DISPLAY'], 2)
689 src.printcolors.print_value(logger, _('Timeout'),
690 src.test_module.DEFAULT_TIMEOUT, 2)
691 src.printcolors.print_value(logger, _("Working dir"), base_dir, 3)
693 # create the test object
694 test_runner = src.test_module.Test(runner.cfg,
699 sessions=options.sessions,
700 launcher=options.launcher,
701 show_desktop=show_desktop)
703 if not test_runner.test_base_found:
708 logger.allowPrintLevel = False
709 retcode = test_runner.run_all_tests()
710 logger.allowPrintLevel = True
712 logger.write(_("Tests finished"), 1)
713 logger.write("\n", 2, False)
715 logger.write(_("\nGenerate the specific test log\n"), 5)
716 log_dir = src.get_log_path(runner.cfg)
717 out_dir = os.path.join(log_dir, "TEST")
718 src.ensure_path_exists(out_dir)
719 name_xml_board = logger.logFileName.split(".")[0] + "_board.xml"
720 historic_xml_path = generate_history_xml_path(runner.cfg, test_base)
722 create_test_report(runner.cfg,
726 xmlname = name_xml_board)
727 xml_board_path = os.path.join(out_dir, name_xml_board)
729 logger.l_logFiles.append(xml_board_path)
730 logger.add_link(os.path.join("TEST", name_xml_board),
733 "Click on the link to get the detailed test results")
734 logger.write("\nTests board file %s\n" % xml_board_path, 1)
736 # Add the historic files into the log files list of the command
737 logger.l_logFiles.append(historic_xml_path)
739 if not options.keeptempdir:
740 logger.write("Removing the temporary directory: rm -rf %s\n" % test_runner.tmp_working_dir, 5)
741 if os.path.exists(test_runner.tmp_working_dir):
742 shutil.rmtree(test_runner.tmp_working_dir)
744 logger.write("NOT Removing the temporary directory: rm -rf %s\n" % test_runner.tmp_working_dir, 5)