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, dest_path, stylesheet, xmlname=""):
232 application_name = config.VARS.application
233 withappli = src.config_has_application(config)
235 root = etree.Element("salome")
236 prod_node = etree.Element("product", name=application_name, build=xmlname)
237 root.append(prod_node)
241 add_simple_node(prod_node, "version_to_download",
242 config.APPLICATION.name)
244 add_simple_node(prod_node, "out_dir", config.APPLICATION.workdir)
247 exec_node = add_simple_node(prod_node, "exec")
248 exec_node.append(etree.Element("env", name="Host", value=config.VARS.node))
249 exec_node.append(etree.Element("env", name="Architecture",
250 value=config.VARS.dist))
251 exec_node.append(etree.Element("env", name="Number of processors",
252 value=str(config.VARS.nb_proc)))
253 exec_node.append(etree.Element("env", name="Begin date",
254 value=src.parse_date(config.VARS.datehour)))
255 exec_node.append(etree.Element("env", name="Command",
256 value=config.VARS.command))
257 exec_node.append(etree.Element("env", name="sat version",
258 value=config.INTERNAL.sat_version))
260 if 'TESTS' in config:
261 tests = add_simple_node(prod_node, "tests")
262 known_errors = add_simple_node(prod_node, "known_errors")
263 new_errors = add_simple_node(prod_node, "new_errors")
264 amend = add_simple_node(prod_node, "amend")
266 for test in config.TESTS:
267 if not tt.has_key(test.testbase):
268 tt[test.testbase] = [test]
270 tt[test.testbase].append(test)
272 for testbase in tt.keys():
273 gn = add_simple_node(tests, "testbase")
274 gn.attrib['name'] = testbase
275 nb, nb_pass, nb_failed, nb_timeout, nb_not_run = 0, 0, 0, 0, 0
278 for test in tt[testbase]:
280 if not grids.has_key(test.grid):
281 mn = add_simple_node(gn, "grid")
282 mn.attrib['name'] = test.grid
283 grids[test.grid] = mn
285 if not sessions.has_key("%s/%s" % (test.grid, test.session)):
286 tyn = add_simple_node(mn, "session")
287 tyn.attrib['name'] = test.session
288 sessions["%s/%s" % (test.grid, test.session)] = tyn
290 for script in test.script:
291 tn = add_simple_node(sessions[
292 "%s/%s" % (test.grid, test.session)], "test")
293 tn.attrib['session'] = test.session
294 tn.attrib['script'] = script.name
295 if 'callback' in script:
297 cnode = add_simple_node(tn, "callback")
298 if src.architecture.is_windows():
301 lambda x: x in string.printable,
304 cnode.text = script.callback.decode(
306 except UnicodeDecodeError as exc:
307 zz = (script.callback[:exc.start] +
309 script.callback[exc.end-2:])
310 cnode = add_simple_node(tn, "callback")
311 cnode.text = zz.decode("UTF-8")
313 # Add the script content
314 cnode = add_simple_node(tn, "content")
315 cnode.text = script.content
317 # Add the script execution log
318 cnode = add_simple_node(tn, "out")
319 cnode.text = script.out
321 if 'amend' in script:
322 cnode = add_simple_node(tn, "amend")
323 cnode.text = script.amend.decode("UTF-8")
326 tn.attrib['exec_time'] = "?"
328 tn.attrib['exec_time'] = "%.3f" % script.time
329 tn.attrib['res'] = script.res
331 if "amend" in script:
332 amend_test = add_simple_node(amend, "atest")
333 amend_test.attrib['name'] = os.path.join(test.grid,
336 amend_test.attrib['reason'] = script.amend.decode(
341 if script.res == src.OK_STATUS: nb_pass += 1
342 elif script.res == src.TIMEOUT_STATUS: nb_timeout += 1
343 elif script.res == src.KO_STATUS: nb_failed += 1
344 else: nb_not_run += 1
346 if "known_error" in script:
347 kf_script = add_simple_node(known_errors, "error")
348 kf_script.attrib['name'] = os.path.join(test.grid,
351 kf_script.attrib['date'] = script.known_error.date
353 'expected'] = script.known_error.expected
355 'comment'] = script.known_error.comment.decode("UTF-8")
356 kf_script.attrib['fixed'] = str(
357 script.known_error.fixed)
358 overdue = datetime.datetime.today().strftime("%Y-%m-"
359 "%d") > script.known_error.expected
361 kf_script.attrib['overdue'] = str(overdue)
363 elif script.res == src.KO_STATUS:
364 new_err = add_simple_node(new_errors, "new_error")
365 script_path = os.path.join(test.grid,
366 test.session, script.name)
367 new_err.attrib['name'] = script_path
368 new_err.attrib['cmd'] = ("sat testerror %s -s %s -c 'my"
369 " comment' -p %s" % \
370 (application_name, script_path, config.VARS.dist))
373 gn.attrib['total'] = str(nb)
374 gn.attrib['pass'] = str(nb_pass)
375 gn.attrib['failed'] = str(nb_failed)
376 gn.attrib['timeout'] = str(nb_timeout)
377 gn.attrib['not_run'] = str(nb_not_run)
379 if len(xmlname) == 0:
380 xmlname = application_name
381 if not xmlname.endswith(".xml"):
384 src.xmlManager.write_report(os.path.join(dest_path, xmlname),
389 def run(args, runner, logger):
390 '''method that is called when salomeTools is called with test parameter.
392 (options, args) = parse_option(args, runner.cfg)
394 with_application = False
395 if runner.cfg.VARS.application != 'None':
396 logger.write(_('Running tests on application %s\n') %
397 src.printcolors.printcLabel(
398 runner.cfg.VARS.application), 1)
399 with_application = True
400 elif not options.base:
401 raise src.SatException(_('A test base is required. Use the --base '
405 # check if environment is loaded
406 if 'KERNEL_ROOT_DIR' in os.environ:
407 logger.write(src.printcolors.printcWarning(_("WARNING: "
408 "SALOME environment already sourced")) + "\n", 1)
411 elif options.launcher:
412 logger.write(src.printcolors.printcWarning(_("Running SALOME "
413 "application.")) + "\n\n", 1)
415 msg = _("Impossible to find any launcher.\nPlease specify an "
416 "application or a launcher")
417 logger.write(src.printcolors.printcError(msg))
422 show_desktop = (options.display and options.display.upper() == "NO")
423 if options.display and options.display != "NO":
424 remote_name = options.display.split(':')[0]
425 if remote_name != "":
426 check_remote_machine(remote_name, logger)
427 # if explicitly set use user choice
428 os.environ['DISPLAY'] = options.display
429 elif 'DISPLAY' not in os.environ:
431 if ('display' in runner.cfg.SITE.test and
432 len(runner.cfg.SITE.test.display) > 0):
433 # use default value for test tool
434 os.environ['DISPLAY'] = runner.cfg.SITE.test.display
436 os.environ['DISPLAY'] = "localhost:0.0"
441 tmp_dir = runner.cfg.SITE.test.tmp_dir_with_application
443 tmp_dir = runner.cfg.SITE.test.tmp_dir
445 # remove previous tmp dir
446 if os.access(tmp_dir, os.F_OK):
448 shutil.rmtree(tmp_dir)
450 logger.error(_("error removing TT_TMP_RESULT %s\n")
454 lines.append("date = '%s'" % runner.cfg.VARS.date)
455 lines.append("hour = '%s'" % runner.cfg.VARS.hour)
456 lines.append("node = '%s'" % runner.cfg.VARS.node)
457 lines.append("arch = '%s'" % runner.cfg.VARS.dist)
459 if 'APPLICATION' in runner.cfg:
460 lines.append("application_info = {}")
461 lines.append("application_info['name'] = '%s'" %
462 runner.cfg.APPLICATION.name)
463 lines.append("application_info['tag'] = '%s'" %
464 runner.cfg.APPLICATION.tag)
465 lines.append("application_info['products'] = %s" %
466 str(runner.cfg.APPLICATION.products))
468 content = "\n".join(lines)
470 # create hash from context information
471 dirname = sha1(content.encode()).hexdigest()
472 base_dir = os.path.join(tmp_dir, dirname)
473 os.makedirs(base_dir)
474 os.environ['TT_TMP_RESULT'] = base_dir
476 # create env_info file
477 f = open(os.path.join(base_dir, 'env_info.py'), "w")
481 # create working dir and bases dir
482 working_dir = os.path.join(base_dir, 'WORK')
483 os.makedirs(working_dir)
484 os.makedirs(os.path.join(base_dir, 'BASES'))
485 os.chdir(working_dir)
487 if 'PYTHONPATH' not in os.environ:
488 os.environ['PYTHONPATH'] = ''
490 for var in os.environ['PYTHONPATH'].split(':'):
491 if var not in sys.path:
494 # launch of the tests
495 #####################
498 test_base = options.base
499 elif with_application and "test_base" in runner.cfg.APPLICATION:
500 test_base = runner.cfg.APPLICATION.test_base.name
502 src.printcolors.print_value(logger, _('Display'), os.environ['DISPLAY'], 2)
503 src.printcolors.print_value(logger, _('Timeout'),
504 runner.cfg.SITE.test.timeout, 2)
505 src.printcolors.print_value(logger, _("Working dir"), base_dir, 3)
507 # create the test object
508 test_runner = src.test_module.Test(runner.cfg,
513 sessions=options.sessions,
514 launcher=options.launcher,
515 show_desktop=show_desktop)
517 if not test_runner.test_base_found:
522 logger.allowPrintLevel = False
523 retcode = test_runner.run_all_tests()
524 logger.allowPrintLevel = True
526 logger.write(_("Tests finished"), 1)
527 logger.write("\n", 2, False)
529 logger.write(_("\nGenerate the specific test log\n"), 5)
530 out_dir = os.path.join(runner.cfg.USER.log_dir, "TEST")
531 src.ensure_path_exists(out_dir)
532 name_xml_board = logger.logFileName.split(".")[0] + "board" + ".xml"
533 create_test_report(runner.cfg,
536 xmlname = name_xml_board)
537 xml_board_path = os.path.join(out_dir, name_xml_board)
538 logger.l_logFiles.append(xml_board_path)
539 logger.add_link(os.path.join("TEST", name_xml_board),
542 "Click on the link to get the detailed test results")
544 logger.write(_("Removing the temporary directory: rm -rf %s\n" % test_runner.tmp_working_dir), 5)
545 if os.path.exists(test_runner.tmp_working_dir):
546 shutil.rmtree(test_runner.tmp_working_dir)