]> SALOME platform Git repositories - tools/sat.git/blob - src/test_module.py
Salome HOME
in logs, collapse by default the logs
[tools/sat.git] / src / test_module.py
1 #!/usr/bin/env python
2 #-*- coding:utf-8 -*-
3 #  Copyright (C) 2010-2013  CEA/DEN
4 #
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.
9 #
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.
14 #
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
18
19 # Python 2/3 compatibility for execfile function
20 try:
21     execfile
22 except:
23     def execfile(somefile, global_vars, local_vars):
24         with open(somefile) as f:
25             code = compile(f.read(), somefile, 'exec')
26             exec(code, global_vars, local_vars)
27
28
29 import os
30 import sys
31 import datetime
32 import shutil
33 import string
34 import imp
35 import subprocess
36
37 from . import fork
38 import src
39
40 # directories not considered as test grids
41 C_IGNORE_GRIDS = ['.git', '.svn', 'RESSOURCES']
42
43 # Get directory to be used for the temporary files.
44 #
45 def getTmpDirDEFAULT():
46     if src.architecture.is_windows():
47         directory = os.getenv("TEMP")
48     else:
49         # for Linux: use /tmp/logs/{user} folder
50         directory = os.path.join( '/tmp', 'logs', os.getenv("USER", "unknown"))
51     return directory
52
53 class Test:
54     def __init__(self,
55                  config,
56                  logger,
57                  tmp_working_dir,
58                  testbase="",
59                  grids=None,
60                  sessions=None,
61                  launcher="",
62                  show_desktop=True):
63         self.grids = grids
64         self.config = config
65         self.logger = logger
66         self.tmp_working_dir = tmp_working_dir
67         self.sessions = sessions
68         self.launcher = launcher
69         self.show_desktop = show_desktop
70
71         res = self.prepare_testbase(testbase)
72         self.test_base_found = True
73         if res == 1:
74             # Fail
75             self.test_base_found = False
76         
77         self.settings = {}
78         self.known_errors = None
79
80         # create section for results
81         self.config.TESTS = src.pyconf.Sequence(self.config)
82
83         self.nb_run = 0
84         self.nb_succeed = 0
85         self.nb_timeout = 0
86         self.nb_not_run = 0
87         self.nb_acknoledge = 0
88
89     def _copy_dir(self, source, target):
90         if self.config.VARS.python >= "2.6":
91             shutil.copytree(source, target,
92                             symlinks=True,
93                             ignore=shutil.ignore_patterns('.git*','.svn*'))
94         else:
95             shutil.copytree(source, target,
96                             symlinks=True)
97
98     def prepare_testbase_from_dir(self, testbase_name, testbase_dir):
99         self.logger.write(_("get test base from dir: %s\n") % \
100                           src.printcolors.printcLabel(testbase_dir), 3)
101         if not os.access(testbase_dir, os.X_OK):
102             raise src.SatException(_("testbase %(name)s (%(dir)s) does not "
103                                      "exist ...\n") % { 'name': testbase_name,
104                                                        'dir': testbase_dir })
105
106         self._copy_dir(testbase_dir,
107                        os.path.join(self.tmp_working_dir, 'BASES', testbase_name))
108
109     def prepare_testbase_from_git(self,
110                                   testbase_name,
111                                   testbase_base,
112                                   testbase_tag):
113         self.logger.write(
114             _("get test base '%(testbase)s' with '%(tag)s' tag from git\n") % {
115                         "testbase" : src.printcolors.printcLabel(testbase_name),
116                         "tag" : src.printcolors.printcLabel(testbase_tag)},
117                           3)
118         try:
119             def set_signal(): # pragma: no cover
120                 """see http://bugs.python.org/issue1652"""
121                 import signal
122                 signal.signal(signal.SIGPIPE, signal.SIG_DFL)
123
124             cmd = "git clone --depth 1 %(base)s %(dir)s"
125             cmd += " && cd %(dir)s"
126             if testbase_tag=='master':
127                 cmd += " && git fetch origin %(branch)s"
128             else:
129                 cmd += " && git fetch origin %(branch)s:%(branch)s"
130             cmd += " && git checkout %(branch)s"
131             cmd = cmd % { 'branch': testbase_tag,
132                          'base': testbase_base,
133                          'dir': testbase_name }
134
135             self.logger.write("> %s\n" % cmd, 5)
136             if src.architecture.is_windows():
137                 # preexec_fn not supported on windows platform
138                 res = subprocess.call(cmd,
139                                 cwd=os.path.join(self.tmp_working_dir, 'BASES'),
140                                 shell=True,
141                                 stdout=self.logger.logTxtFile,
142                                 stderr=subprocess.PIPE)
143             else:
144                 res = subprocess.call(cmd,
145                                 cwd=os.path.join(self.tmp_working_dir, 'BASES'),
146                                 shell=True,
147                                 preexec_fn=set_signal,
148                                 stdout=self.logger.logTxtFile,
149                                 stderr=subprocess.PIPE)
150             if res != 0:
151                 raise src.SatException(_("Error: unable to get test base "
152                                          "'%(name)s' from git '%(repo)s'.") % \
153                                        { 'name': testbase_name,
154                                         'repo': testbase_base })
155
156         except OSError:
157             self.logger.error(_("git is not installed. exiting...\n"))
158             sys.exit(0)
159
160     def prepare_testbase_from_svn(self, user, testbase_name, testbase_base):
161         self.logger.write(_("get test base '%s' from svn\n") % \
162                           src.printcolors.printcLabel(testbase_name), 3)
163         try:
164             def set_signal(): # pragma: no cover
165                 """see http://bugs.python.org/issue1652"""
166                 import signal
167                 signal.signal(signal.SIGPIPE, signal.SIG_DFL)
168
169             cmd = "svn checkout --username %(user)s %(base)s %(dir)s"
170             cmd = cmd % { 'user': user,
171                          'base': testbase_base,
172                          'dir': testbase_name }
173
174             self.logger.write("> %s\n" % cmd, 5)
175             if src.architecture.is_windows():
176                 # preexec_fn not supported on windows platform
177                 res = subprocess.call(cmd,
178                                 cwd=os.path.join(self.tmp_working_dir, 'BASES'),
179                                 shell=True,
180                                 stdout=self.logger.logTxtFile,
181                                 stderr=subprocess.PIPE)
182             else:
183                 res = subprocess.call(cmd,
184                                 cwd=os.path.join(self.tmp_working_dir, 'BASES'),
185                                 shell=True,
186                                 preexec_fn=set_signal,
187                                 stdout=self.logger.logTxtFile,
188                                 stderr=subprocess.PIPE)
189
190             if res != 0:
191                 raise src.SatException(_("Error: unable to get test base '%(nam"
192                                          "e)s' from svn '%(repo)s'.") % \
193                                        { 'name': testbase_name,
194                                         'repo': testbase_base })
195
196         except OSError:
197             self.logger.error(_("svn is not installed. exiting...\n"))
198             sys.exit(0)
199
200     ##
201     # Configure tests base.
202     def prepare_testbase(self, test_base_name):
203         src.printcolors.print_value(self.logger,
204                                     _("Test base"),
205                                     test_base_name,
206                                     3)
207         self.logger.write("\n", 3, False)
208
209         # search for the test base
210         test_base_info = None
211         for project_name in self.config.PROJECTS.projects:
212             project_info = self.config.PROJECTS.projects[project_name]
213             if "test_bases" not in project_info:
214                 continue
215             for t_b_info in project_info.test_bases:
216                 if t_b_info.name == test_base_name:
217                     test_base_info = t_b_info
218         
219         if not test_base_info:
220             if os.path.exists(test_base_name):
221                 self.prepare_testbase_from_dir("DIR", test_base_name)
222                 self.currentTestBase = "DIR"
223                 return 0
224         
225         if not test_base_info:
226             message = (_("########## ERROR: test base '%s' not found\n") % 
227                        test_base_name)
228             self.logger.write("%s\n" % src.printcolors.printcError(message))
229             return 1
230
231         if test_base_info.get_sources == "dir":
232             self.prepare_testbase_from_dir(test_base_name,
233                                            test_base_info.info.dir)
234         elif test_base_info.get_sources == "git":
235             self.prepare_testbase_from_git(test_base_name,
236                                        test_base_info.info.base,
237                                        self.config.APPLICATION.test_base.tag)
238         elif test_base_info.get_sources == "svn":
239             svn_user = src.get_cfg_param(test_base_info.svn_info,
240                                          "svn_user",
241                                          self.config.USER.svn_user)
242             self.prepare_testbase_from_svn(svn_user,
243                                        test_base_name,
244                                        test_base_info.info.base)
245         else:
246             raise src.SatException(_("unknown source type '%(type)s' for test b"
247                                      "ase '%(base)s' ...\n") % {
248                                         'type': test_base_info.get_sources,
249                                         'base': test_base_name })
250
251         self.currentTestBase = test_base_name
252
253     ##
254     # Searches if the script is declared in known errors pyconf.
255     # Update the status if needed.
256     def search_known_errors(self, status, test_grid, test_session, test):
257         test_path = os.path.join(test_grid, test_session, test)
258         if not src.config_has_application(self.config):
259             return status, []
260
261         if self.known_errors is None:
262             return status, []
263
264         platform = self.config.VARS.arch
265         application = self.config.VARS.application
266         error = self.known_errors.get_error(test_path, application, platform)
267         if error is None:
268             return status, []
269         
270         if status == src.OK_STATUS:
271             if not error.fixed:
272                 # the error is fixed
273                 self.known_errors.fix_error(error)
274                 #import testerror
275                 #testerror.write_test_failures(
276                 #                        self.config.TOOLS.testerror.file_path,
277                 #                        self.known_errors.errors)
278             return status, [ error.date,
279                             error.expected,
280                             error.comment,
281                             error.fixed ]
282
283         if error.fixed:
284             self.known_errors.unfix_error(error)
285             #import testerror
286             #testerror.write_test_failures(self.config.TOOLS.testerror.file_path,
287             #                              self.known_errors.errors)
288
289         delta = self.known_errors.get_expecting_days(error)
290         kfres = [ error.date, error.expected, error.comment, error.fixed ]
291         if delta < 0:
292             return src.KO_STATUS, kfres
293         return src.KNOWNFAILURE_STATUS, kfres
294
295     ##
296     # Read the *.result.py files.
297     def read_results(self, listTest, has_timed_out):
298         results = {}
299         for test in listTest:
300             resfile = os.path.join(self.currentDir,
301                                    self.currentgrid,
302                                    self.currentsession,
303                                    test[:-3] + ".result.py")
304
305             # check if <test>.result.py file exists
306             if not os.path.exists(resfile):
307                 results[test] = ["?", -1, "", []]
308             else:
309                 gdic, ldic = {}, {}
310                 execfile(resfile, gdic, ldic)
311
312                 status = src.TIMEOUT_STATUS
313                 if not has_timed_out:
314                     status = src.KO_STATUS
315
316                 if ldic.has_key('status'):
317                     status = ldic['status']
318
319                 expected = []
320                 if status == src.KO_STATUS or status == src.OK_STATUS:
321                     status, expected = self.search_known_errors(status,
322                                                             self.currentgrid,
323                                                             self.currentsession,
324                                                             test)
325
326                 callback = ""
327                 if ldic.has_key('callback'):
328                     callback = ldic['callback']
329                 elif status == src.KO_STATUS:
330                     callback = "CRASH"
331
332                 exec_time = -1
333                 if ldic.has_key('time'):
334                     try:
335                         exec_time = float(ldic['time'])
336                     except:
337                         pass
338
339                 results[test] = [status, exec_time, callback, expected]
340             
341             # check if <test>.py file exists
342             testfile = os.path.join(self.currentDir,
343                                    self.currentgrid,
344                                    self.currentsession,
345                                    test)
346             
347             if not os.path.exists(testfile):
348                 results[test].append('')
349             else:
350                 text = open(testfile, "r").read()
351                 results[test].append(text)
352
353             # check if <test>.out.py file exists
354             outfile = os.path.join(self.currentDir,
355                                    self.currentgrid,
356                                    self.currentsession,
357                                    test[:-3] + ".out.py")
358             
359             if not os.path.exists(outfile):
360                 results[test].append('')
361             else:
362                 text = open(outfile, "r").read()
363                 results[test].append(text)
364
365         return results
366
367     ##
368     # Generates the script to be run by Salome.
369     # This python script includes init and close statements and a loop
370     # calling all the scripts of a single directory.
371     def generate_script(self, listTest, script_path, ignoreList):
372         # open template file
373         template_file = open(os.path.join(self.config.VARS.srcDir,
374                                           "test",
375                                           "scriptTemplate.py"), 'r')
376         template = string.Template(template_file.read())
377         
378         # create substitution dictionary
379         d = dict()
380         d['resourcesWay'] = os.path.join(self.currentDir, 'RESSOURCES')
381         d['tmpDir'] = os.path.join(self.tmp_working_dir, 'WORK')
382         d['toolsWay'] = os.path.join(self.config.VARS.srcDir, "test")
383         d['sessionDir'] = os.path.join(self.currentDir,
384                                     self.currentgrid,
385                                     self.currentsession)
386         d['resultFile'] = os.path.join(self.tmp_working_dir,
387                                        'WORK',
388                                        'exec_result')
389         d['listTest'] = listTest
390         d['sessionName'] = self.currentsession
391         d['ignore'] = ignoreList
392
393         # create script with template
394         script = open(script_path, 'w')
395         script.write(template.safe_substitute(d))
396         script.close()
397
398     # Find the getTmpDir function that gives access to *pidict file directory.
399     # (the *pidict file exists when SALOME is launched) 
400     def get_tmp_dir(self):
401         # Rare case where there is no KERNEL in grid list 
402         # (for example MED_STANDALONE)
403         if ('APPLICATION' in self.config 
404                 and 'KERNEL' not in self.config.APPLICATION.products 
405                 and 'KERNEL_ROOT_DIR' not in os.environ):
406             return getTmpDirDEFAULT
407         
408         # Case where "sat test" is launched in an existing SALOME environment
409         if 'KERNEL_ROOT_DIR' in os.environ:
410             root_dir =  os.environ['KERNEL_ROOT_DIR']
411         
412         if ('APPLICATION' in self.config 
413                 and 'KERNEL' in self.config.APPLICATION.products):
414             root_dir = src.product.get_product_config(self.config,
415                                                       "KERNEL").install_dir
416
417         # Case where there the appli option is called (with path to launcher)
418         if len(self.launcher) > 0:
419             # There are two cases : The old application (runAppli) 
420             # and the new one
421             launcherName = os.path.basename(self.launcher)
422             launcherDir = os.path.dirname(self.launcher)
423             if launcherName == 'runAppli':
424                 # Old application
425                 cmd = "for i in " + launcherDir + "/env.d/*.sh; do source ${i};"
426                 " done ; echo $KERNEL_ROOT_DIR"
427             else:
428                 # New application
429                 cmd = "echo -e 'import os\nprint os.environ[\"KERNEL_ROOT_DIR\""
430                 "]' > tmpscript.py; %s shell tmpscript.py" % self.launcher
431             root_dir = subprocess.Popen(cmd,
432                             stdout=subprocess.PIPE,
433                             shell=True,
434                             executable='/bin/bash').communicate()[0].split()[-1]
435         
436         # import grid salome_utils from KERNEL that gives 
437         # the right getTmpDir function
438         
439         (file_, pathname, description) = imp.find_module("salome_utils",
440                                                          [os.path.join(root_dir,
441                                                                     'bin',
442                                                                     'salome')])
443         try:
444             grid = imp.load_module("salome_utils",
445                                      file_,
446                                      pathname,
447                                      description)
448             return grid.getLogDir
449         except:
450             grid = imp.load_module("salome_utils",
451                                      file_,
452                                      pathname,
453                                      description)
454             return grid.getTmpDir
455         finally:
456             if file_:
457                 file_.close()
458
459
460     def get_test_timeout(self, test_name, default_value):
461         if ("timeout" in self.settings and 
462                 test_name in self.settings["timeout"]):
463             return self.settings["timeout"][test_name]
464
465         return default_value
466
467     def generate_launching_commands(self):
468         # Case where "sat test" is launched in an existing SALOME environment
469         if 'KERNEL_ROOT_DIR' in os.environ:
470             binSalome = "runSalome"
471             binPython = "python"
472             killSalome = "killSalome.py"
473         
474         # Rare case where there is no KERNEL in grid list 
475         # (for example MED_STANDALONE)
476         if ('APPLICATION' in self.config and 
477                 'KERNEL' not in self.config.APPLICATION.products):
478             binSalome = "runSalome"
479             binPython = "python" 
480             killSalome = "killSalome.py"   
481             src.environment.load_environment(self.config, False, self.logger)         
482             return binSalome, binPython, killSalome
483         
484         # Case where there the appli option is called (with path to launcher)
485         if len(self.launcher) > 0:
486             # There are two cases : The old application (runAppli) 
487             # and the new one
488             launcherName = os.path.basename(self.launcher)
489             launcherDir = os.path.dirname(self.launcher)
490             if launcherName == 'runAppli':
491                 # Old application
492                 binSalome = self.launcher
493                 binPython = ("for i in " +
494                              launcherDir +
495                              "/env.d/*.sh; do source ${i}; done ; python")
496                 killSalome = ("for i in " +
497                         launcherDir +
498                         "/env.d/*.sh; do source ${i}; done ; killSalome.py'")
499                 return binSalome, binPython, killSalome
500             else:
501                 # New application
502                 binSalome = self.launcher
503                 binPython = self.launcher + ' shell'
504                 killSalome = self.launcher + ' killall'
505                 return binSalome, binPython, killSalome
506
507         # SALOME version detection and APPLI repository detection
508         VersionSalome = src.get_salome_version(self.config)
509         appdir = 'APPLI'
510         if "APPLI" in self.config and "application_name" in self.config.APPLI:
511             appdir = self.config.APPLI.application_name
512         
513         # Case where SALOME has NOT the launcher that uses the SalomeContext API
514         if VersionSalome < 730:
515             binSalome = os.path.join(self.config.APPLI.grid_appli_install_dir,
516                                      appdir,
517                                      "runAppli")
518             binPython = "python"
519             killSalome = "killSalome.py"
520             src.environment.load_environment(self.config, False, self.logger)           
521             return binSalome, binPython, killSalome
522         
523         # Case where SALOME has the launcher that uses the SalomeContext API
524         if VersionSalome >= 730:            
525             if 'profile' not in self.config.APPLICATION:
526                 # Before revision of application concept
527                 launcher_name = self.config.APPLI.launch_alias_name
528                 binSalome = os.path.join(self.config.APPLICATION.workdir,
529                                          appdir,
530                                          launcher_name)
531             else:
532                 # After revision of application concept
533                 launcher_name = self.config.APPLICATION.profile.launcher_name
534                 binSalome = os.path.join(self.config.APPLICATION.workdir,
535                                          launcher_name)
536             
537             if src.architecture.is_windows():
538                 binSalome += '.bat'
539
540             binPython = binSalome + ' shell'
541             killSalome = binSalome + ' killall'
542             return binSalome, binPython, killSalome
543                 
544         return binSalome, binPython, killSalome
545         
546
547     ##
548     # Runs tests of a session (using a single instance of Salome).
549     def run_tests(self, listTest, ignoreList):
550         out_path = os.path.join(self.currentDir,
551                                 self.currentgrid,
552                                 self.currentsession)
553         sessionname = "%s/%s" % (self.currentgrid, self.currentsession)
554         time_out = self.get_test_timeout(sessionname,
555                                          self.config.SITE.test.timeout)
556
557         time_out_salome = src.get_cfg_param(self.config.SITE.test,
558                                             "timeout_app",
559                                             self.config.SITE.test.timeout)
560
561         # generate wrapper script
562         script_path = os.path.join(out_path, 'wrapperScript.py')
563         self.generate_script(listTest, script_path, ignoreList)
564
565         tmpDir = self.get_tmp_dir()
566
567         binSalome, binPython, killSalome = self.generate_launching_commands()
568         if self.settings.has_key("run_with_grids") \
569            and self.settings["run_with_grids"].has_key(sessionname):
570             binSalome = (binSalome +
571                          " -m %s" % self.settings["run_with_grids"][sessionname])
572
573         logWay = os.path.join(self.tmp_working_dir, "WORK", "log_cxx")
574
575         status = False
576         elapsed = -1
577         if self.currentsession.startswith("NOGUI_"):
578             # runSalome -t (bash)
579             status, elapsed = fork.batch(binSalome, self.logger,
580                                         os.path.join(self.tmp_working_dir,
581                                                      "WORK"),
582                                         [ "-t",
583                                          "--shutdown-server=1",
584                                          script_path ],
585                                         delai=time_out,
586                                         log=logWay)
587
588         elif self.currentsession.startswith("PY_"):
589             # python script.py
590             status, elapsed = fork.batch(binPython, self.logger,
591                                           os.path.join(self.tmp_working_dir,
592                                                        "WORK"),
593                                           [script_path],
594                                           delai=time_out, log=logWay)
595
596         else:
597             opt = "-z 0"
598             if self.show_desktop: opt = "--show-desktop=0"
599             status, elapsed = fork.batch_salome(binSalome,
600                                                  self.logger,
601                                                  os.path.join(
602                                                         self.tmp_working_dir,
603                                                         "WORK"),
604                                                  [ opt,
605                                                   "--shutdown-server=1",
606                                                   script_path ],
607                                                  getTmpDir=tmpDir,
608                                                  fin=killSalome,
609                                                  delai=time_out,
610                                                  log=logWay,
611                                                  delaiapp=time_out_salome)
612
613         self.logger.write("status = %s, elapsed = %s\n" % (status, elapsed),
614                           5)
615
616         # create the test result to add in the config object
617         test_info = src.pyconf.Mapping(self.config)
618         test_info.testbase = self.currentTestBase
619         test_info.grid = self.currentgrid
620         test_info.session = self.currentsession
621         test_info.script = src.pyconf.Sequence(self.config)
622
623         script_results = self.read_results(listTest, elapsed == time_out)
624         for sr in sorted(script_results.keys()):
625             self.nb_run += 1
626
627             # create script result
628             script_info = src.pyconf.Mapping(self.config)
629             script_info.name = sr
630             script_info.res = script_results[sr][0]
631             script_info.time = script_results[sr][1]
632             if script_info.res == src.TIMEOUT_STATUS:
633                 script_info.time = time_out
634             if script_info.time < 1e-3: script_info.time = 0
635
636             callback = script_results[sr][2]
637             if script_info.res != src.OK_STATUS and len(callback) > 0:
638                 script_info.callback = callback
639
640             kfres = script_results[sr][3]
641             if len(kfres) > 0:
642                 script_info.known_error = src.pyconf.Mapping(self.config)
643                 script_info.known_error.date = kfres[0]
644                 script_info.known_error.expected = kfres[1]
645                 script_info.known_error.comment = kfres[2]
646                 script_info.known_error.fixed = kfres[3]
647             
648             script_info.content = script_results[sr][4]
649             script_info.out = script_results[sr][5]
650             
651             # add it to the list of results
652             test_info.script.append(script_info, '')
653
654             # display the results
655             if script_info.time > 0:
656                 exectime = "(%7.3f s)" % script_info.time
657             else:
658                 exectime = ""
659
660             sp = "." * (35 - len(script_info.name))
661             self.logger.write(self.write_test_margin(3), 3)
662             self.logger.write("script %s %s %s %s\n" % (
663                                 src.printcolors.printcLabel(script_info.name),
664                                 sp,
665                                 src.printcolors.printc(script_info.res),
666                                 exectime), 3, False)
667             if script_info and len(callback) > 0:
668                 self.logger.write("Exception in %s\n%s\n" % \
669                     (script_info.name,
670                      src.printcolors.printcWarning(callback)), 2, False)
671
672             if script_info.res == src.OK_STATUS:
673                 self.nb_succeed += 1
674             elif script_info.res == src.KNOWNFAILURE_STATUS:
675                 self.nb_acknoledge += 1
676             elif script_info.res == src.TIMEOUT_STATUS:
677                 self.nb_timeout += 1
678             elif script_info.res == src.NA_STATUS:
679                 self.nb_run -= 1
680             elif script_info.res == "?":
681                 self.nb_not_run += 1
682
683         self.config.TESTS.append(test_info, '')
684
685     ##
686     # Runs all tests of a session.
687     def run_session_tests(self):
688        
689         self.logger.write(self.write_test_margin(2), 3)
690         self.logger.write("Session = %s\n" % src.printcolors.printcLabel(
691                                                     self.currentsession), 3, False)
692
693         # prepare list of tests to run
694         tests = os.listdir(os.path.join(self.currentDir,
695                                         self.currentgrid,
696                                         self.currentsession))
697         tests = filter(lambda l: l.endswith(".py"), tests)
698         tests = sorted(tests, key=str.lower)
699
700         # build list of known failures
701         cat = "%s/%s/" % (self.currentgrid, self.currentsession)
702         ignoreDict = {}
703         for k in self.ignore_tests.keys():
704             if k.startswith(cat):
705                 ignoreDict[k[len(cat):]] = self.ignore_tests[k]
706
707         self.run_tests(tests, ignoreDict)
708
709     ##
710     # Runs all tests of a grid.
711     def run_grid_tests(self):
712         self.logger.write(self.write_test_margin(1), 3)
713         self.logger.write("grid = %s\n" % src.printcolors.printcLabel(
714                                                 self.currentgrid), 3, False)
715
716         grid_path = os.path.join(self.currentDir, self.currentgrid)
717
718         sessions = []
719         if self.sessions is not None:
720             sessions = self.sessions # user choice
721         else:
722             # use all scripts in grid
723             sessions = filter(lambda l: l not in C_IGNORE_GRIDS,
724                            os.listdir(grid_path))
725             sessions = filter(lambda l: os.path.isdir(os.path.join(grid_path,
726                                                                 l)), sessions)
727
728         sessions = sorted(sessions, key=str.lower)
729         for session_ in sessions:
730             if not os.path.exists(os.path.join(grid_path, session_)):
731                 self.logger.write(self.write_test_margin(2), 3)
732                 self.logger.write(src.printcolors.printcWarning("Session %s not"
733                                         " found" % session_) + "\n", 3, False)
734             else:
735                 self.currentsession = session_
736                 self.run_session_tests()
737
738     ##
739     # Runs test testbase.
740     def run_testbase_tests(self):
741         res_dir = os.path.join(self.currentDir, "RESSOURCES")
742         os.environ['PYTHONPATH'] =  (res_dir + 
743                                      os.pathsep + 
744                                      os.environ['PYTHONPATH'])
745         os.environ['TT_BASE_RESSOURCES'] = res_dir
746         src.printcolors.print_value(self.logger,
747                                     "TT_BASE_RESSOURCES",
748                                     res_dir,
749                                     4)
750         self.logger.write("\n", 4, False)
751
752         self.logger.write(self.write_test_margin(0), 3)
753         testbase_label = "Test base = %s\n" % src.printcolors.printcLabel(
754                                                         self.currentTestBase)
755         self.logger.write(testbase_label, 3, False)
756         self.logger.write("-" * len(src.printcolors.cleancolor(testbase_label)),
757                           3)
758         self.logger.write("\n", 3, False)
759
760         # load settings
761         settings_file = os.path.join(res_dir, "test_settings.py")
762         if os.path.exists(settings_file):
763             gdic, ldic = {}, {}
764             execfile(settings_file, gdic, ldic)
765             self.logger.write(_("Load test settings\n"), 3)
766             self.settings = ldic['settings_dic']
767             self.ignore_tests = ldic['known_failures_list']
768             if isinstance(self.ignore_tests, list):
769                 self.ignore_tests = {}
770                 self.logger.write(src.printcolors.printcWarning("known_failur"
771                   "es_list must be a dictionary (not a list)") + "\n", 1, False)
772         else:
773             self.ignore_tests = {}
774             self.settings.clear()
775
776         # read known failures pyconf
777         if "testerror" in self.config.SITE:
778             #import testerror
779             #self.known_errors = testerror.read_test_failures(
780             #                            self.config.TOOLS.testerror.file_path,
781             #                            do_error=False)
782             pass
783         else:
784             self.known_errors = None
785
786         if self.grids is not None:
787             grids = self.grids # given by user
788         else:
789             # select all the grids (i.e. directories) in the directory
790             grids = filter(lambda l: l not in C_IGNORE_GRIDS,
791                              os.listdir(self.currentDir))
792             grids = filter(lambda l: os.path.isdir(
793                                         os.path.join(self.currentDir, l)),
794                              grids)
795
796         grids = sorted(grids, key=str.lower)
797         for grid in grids:
798             if not os.path.exists(os.path.join(self.currentDir, grid)):
799                 self.logger.write(self.write_test_margin(1), 3)
800                 self.logger.write(src.printcolors.printcWarning(
801                             "grid %s does not exist\n" % grid), 3, False)
802             else:
803                 self.currentgrid = grid
804                 self.run_grid_tests()
805
806     def run_script(self, script_name):
807         if ('APPLICATION' in self.config and 
808                 script_name in self.config.APPLICATION):
809             script = self.config.APPLICATION[script_name]
810             if len(script) == 0:
811                 return
812
813             self.logger.write("\n", 2, False)
814             if not os.path.exists(script):
815                 self.logger.write(src.printcolors.printcWarning("WARNING: scrip"
816                                         "t not found: %s" % script) + "\n", 2)
817             else:
818                 self.logger.write(src.printcolors.printcHeader("----------- sta"
819                                             "rt %s" % script_name) + "\n", 2)
820                 self.logger.write("Run script: %s\n" % script, 2)
821                 subprocess.Popen(script, shell=True).wait()
822                 self.logger.write(src.printcolors.printcHeader("----------- end"
823                                                 " %s" % script_name) + "\n", 2)
824
825     def run_all_tests(self):
826         initTime = datetime.datetime.now()
827
828         self.run_script('test_setup')
829         self.logger.write("\n", 2, False)
830
831         self.logger.write(src.printcolors.printcHeader(
832                                             _("=== STARTING TESTS")) + "\n", 2)
833         self.logger.write("\n", 2, False)
834         self.currentDir = os.path.join(self.tmp_working_dir,
835                                        'BASES',
836                                        self.currentTestBase)
837         self.run_testbase_tests()
838
839         # calculate total execution time
840         totalTime = datetime.datetime.now() - initTime
841         totalTime -= datetime.timedelta(microseconds=totalTime.microseconds)
842         self.logger.write("\n", 2, False)
843         self.logger.write(src.printcolors.printcHeader(_("=== END TESTS")), 2)
844         self.logger.write(" %s\n" % src.printcolors.printcInfo(str(totalTime)),
845                           2,
846                           False)
847
848         #
849         # Start the tests
850         #
851         self.run_script('test_cleanup')
852         self.logger.write("\n", 2, False)
853
854         # evaluate results
855         res_count = "%d / %d" % (self.nb_succeed,
856                                  self.nb_run - self.nb_acknoledge)
857
858         res_out = _("Tests Results: %(succeed)d / %(total)d\n") % \
859             { 'succeed': self.nb_succeed, 'total': self.nb_run }
860         if self.nb_succeed == self.nb_run:
861             res_out = src.printcolors.printcSuccess(res_out)
862         else:
863             res_out = src.printcolors.printcError(res_out)
864         self.logger.write(res_out, 1)
865
866         if self.nb_timeout > 0:
867             self.logger.write(_("%d tests TIMEOUT\n") % self.nb_timeout, 1)
868             res_count += " TO: %d" % self.nb_timeout
869         if self.nb_not_run > 0:
870             self.logger.write(_("%d tests not executed\n") % self.nb_not_run, 1)
871             res_count += " NR: %d" % self.nb_not_run
872
873         status = src.OK_STATUS
874         if self.nb_run - self.nb_succeed - self.nb_acknoledge > 0:
875             status = src.KO_STATUS
876         elif self.nb_acknoledge:
877             status = src.KNOWNFAILURE_STATUS
878         
879         self.logger.write(_("Status: %s\n" % status), 3)
880
881         return self.nb_run - self.nb_succeed - self.nb_acknoledge
882
883     ##
884     # Write margin to show test results.
885     def write_test_margin(self, tab):
886         if tab == 0:
887             return ""
888         return "|   " * (tab - 1) + "+ "
889