The Gaudi Framework  v39r0 (5b8b5eda)
BaseTest.py
Go to the documentation of this file.
1 
11 
12 import json
13 import logging
14 import os
15 import platform
16 import re
17 import signal
18 import sys
19 import threading
20 import time
21 from datetime import datetime, timedelta
22 from html import escape as escape_for_html
23 from subprocess import PIPE, STDOUT, Popen
24 from tempfile import NamedTemporaryFile, mkdtemp
25 from unittest import TestCase
26 
27 if sys.version_info < (3, 5):
28  # backport of 'backslashreplace' handling of UnicodeDecodeError
29  # to Python < 3.5
30  from codecs import backslashreplace_errors, register_error
31 
33  if isinstance(exc, UnicodeDecodeError):
34  code = hex(ord(exc.object[exc.start]))
35  return ("\\" + code[1:], exc.start + 1)
36  else:
37  return backslashreplace_errors(exc)
38 
39  register_error("backslashreplace", _new_backslashreplace_errors)
40  del register_error
41  del backslashreplace_errors
42  del _new_backslashreplace_errors
43 
44 SKIP_RETURN_CODE = 77
45 
46 # default of 100MB
47 OUTPUT_LIMIT = int(os.environ.get("GAUDI_TEST_STDOUT_LIMIT", 100 * 1024**2))
48 
49 
50 def sanitize_for_xml(data):
51  """
52  Take a string with invalid ASCII/UTF characters and quote them so that the
53  string can be used in an XML text.
54 
55  >>> sanitize_for_xml('this is \x1b')
56  'this is [NON-XML-CHAR-0x1B]'
57  """
58  bad_chars = re.compile("[\x00-\x08\x0b\x0c\x0e-\x1f\ud800-\udfff\ufffe\uffff]")
59 
60  def quote(match):
61  "helper function"
62  return "".join("[NON-XML-CHAR-0x%2X]" % ord(c) for c in match.group())
63 
64  return bad_chars.sub(quote, data)
65 
66 
67 def dumpProcs(name):
68  """helper to debug GAUDI-1084, dump the list of processes"""
69  from getpass import getuser
70 
71  if "WORKSPACE" in os.environ:
72  p = Popen(["ps", "-fH", "-U", getuser()], stdout=PIPE)
73  with open(os.path.join(os.environ["WORKSPACE"], name), "wb") as f:
74  f.write(p.communicate()[0])
75 
76 
77 def kill_tree(ppid, sig):
78  """
79  Send a signal to a process and all its child processes (starting from the
80  leaves).
81  """
82  log = logging.getLogger("kill_tree")
83  ps_cmd = ["ps", "--no-headers", "-o", "pid", "--ppid", str(ppid)]
84  # Note: start in a clean env to avoid a freeze with libasan.so
85  # See https://sourceware.org/bugzilla/show_bug.cgi?id=27653
86  get_children = Popen(ps_cmd, stdout=PIPE, stderr=PIPE, env={})
87  children = map(int, get_children.communicate()[0].split())
88  for child in children:
89  kill_tree(child, sig)
90  try:
91  log.debug("killing process %d", ppid)
92  os.kill(ppid, sig)
93  except OSError as err:
94  if err.errno != 3: # No such process
95  raise
96  log.debug("no such process %d", ppid)
97 
98 
99 # -------------------------------------------------------------------------#
100 
101 
102 class BaseTest(object):
103  _common_tmpdir = None
104 
105  def __init__(self):
106  self.program = ""
107  self.args = []
108  self.reference = ""
109  self.error_reference = ""
110  self.options = ""
111  self.stderr = ""
112  self.timeout = 600
113  self.exit_code = None
114  self.environment = dict(os.environ)
116  self.signal = None
117  self.workdir = os.curdir
118  self.use_temp_dir = False
119  # Variables not for users
120  self.status = None
121  self.name = ""
122  self.causes = []
123  self.result = Result(self)
124  self.returnedCode = 0
125  self.out = ""
126  self.err = ""
127  self.proc = None
128  self.stack_trace = None
129  self.basedir = os.getcwd()
130  self.validate_time = None
131 
132  def run(self):
133  logging.debug("running test %s", self.name)
134 
135  self.result = Result(
136  {
137  "CAUSE": None,
138  "EXCEPTION": None,
139  "RESOURCE": None,
140  "TARGET": None,
141  "TRACEBACK": None,
142  "START_TIME": None,
143  "END_TIME": None,
144  "TIMEOUT_DETAIL": None,
145  }
146  )
147 
148  if self.options:
149  if re.search(
150  r"from\s+Gaudi.Configuration\s+import\s+\*|"
151  r"from\s+Configurables\s+import",
152  self.options,
153  ):
154  suffix, lang = ".py", "python"
155  else:
156  suffix, lang = ".opts", "c++"
157  self.result["Options"] = (
158  '<pre><code class="language-{}">{}</code></pre>'.format(
159  lang, escape_for_html(self.options)
160  )
161  )
162  optionFile = NamedTemporaryFile(suffix=suffix)
163  optionFile.file.write(self.options.encode("utf-8"))
164  optionFile.seek(0)
165  self.args.append(RationalizePath(optionFile.name))
166 
167  platform_id = (
168  self.environment.get("BINARY_TAG")
169  or self.environment.get("CMTCONFIG")
170  or platform.platform()
171  )
172  # If at least one regex matches we skip the test.
173  skip_test = bool(
174  [
175  None
176  for prex in self.unsupported_platforms
177  if re.search(prex, platform_id)
178  ]
179  )
180 
181  if not skip_test:
182  # handle working/temporary directory options
183  workdir = self.workdir
184  if self.use_temp_dir:
185  if self._common_tmpdir:
186  workdir = self._common_tmpdir
187  else:
188  workdir = mkdtemp()
189 
190  # prepare the command to execute
191  prog = ""
192  if self.program != "":
193  prog = self.program
194  elif "GAUDIEXE" in self.environment:
195  prog = self.environment["GAUDIEXE"]
196  else:
197  prog = "Gaudi.exe"
198 
199  prog_ext = os.path.splitext(prog)[1]
200  if prog_ext not in [".exe", ".py", ".bat"]:
201  prog += ".exe"
202  prog_ext = ".exe"
203 
204  prog = which(prog) or prog
205 
206  args = list(map(RationalizePath, self.args))
207 
208  if prog_ext == ".py":
209  params = ["python3", RationalizePath(prog)] + args
210  else:
211  params = [RationalizePath(prog)] + args
212 
213  # we need to switch directory because the validator expects to run
214  # in the same dir as the program
215  os.chdir(workdir)
216 
217  tmp_streams = {
218  "stdout": NamedTemporaryFile(),
219  "stderr": NamedTemporaryFile(),
220  }
221 
222  # launching test in a different thread to handle timeout exception
223  def target():
224  logging.debug("executing %r in %s", params, workdir)
225  self.proc = Popen(
226  params,
227  stdout=tmp_streams["stdout"],
228  stderr=tmp_streams["stderr"],
229  env=self.environment,
230  )
231  logging.debug("(pid: %d)", self.proc.pid)
232  self.proc.communicate()
233  tmp_streams["stdout"].seek(0)
234  self.out = (
235  tmp_streams["stdout"]
236  .read()
237  .decode("utf-8", errors="backslashreplace")
238  )
239  tmp_streams["stderr"].seek(0)
240  self.err = (
241  tmp_streams["stderr"]
242  .read()
243  .decode("utf-8", errors="backslashreplace")
244  )
245 
246  thread = threading.Thread(target=target)
247  thread.start()
248  # checking for timeout and stdout/err cutoff
249  when_to_stop = datetime.now() + timedelta(seconds=self.timeout)
250  too_big_stream = None
251  while (
252  datetime.now() < when_to_stop
253  and thread.is_alive()
254  and not too_big_stream
255  ):
256  # we check stdout and stderr size a few times per second
257  thread.join(0.1)
258  # if we are done, there is no need to check output size
259  if thread.is_alive():
260  for stream in tmp_streams:
261  if os.path.getsize(tmp_streams[stream].name) > OUTPUT_LIMIT:
262  too_big_stream = stream
263 
264  if thread.is_alive():
265  if not too_big_stream:
266  logging.debug(
267  "time out in test %s (pid %d)", self.name, self.proc.pid
268  )
269  # get the stack trace of the stuck process
270  cmd = [
271  "gdb",
272  "--pid",
273  str(self.proc.pid),
274  "--batch",
275  "--eval-command=thread apply all backtrace",
276  ]
277  gdb = Popen(cmd, stdin=PIPE, stdout=PIPE, stderr=STDOUT)
278  self.stack_trace = gdb.communicate()[0].decode(
279  "utf-8", errors="backslashreplace"
280  )
281  self.causes.append("timeout")
282  else:
283  logging.debug(
284  "too big %s detected (pid %d)", too_big_stream, self.proc.pid
285  )
286  self.result[f"{too_big_stream} limit"] = str(OUTPUT_LIMIT)
287  self.result[f"{too_big_stream} size"] = str(
288  os.path.getsize(tmp_streams[too_big_stream].name)
289  )
290  self.causes.append(f"too big {too_big_stream}")
291 
292  kill_tree(self.proc.pid, signal.SIGTERM)
293  thread.join(60)
294  if thread.is_alive():
295  kill_tree(self.proc.pid, signal.SIGKILL)
296 
297  else:
298  self.returnedCode = self.proc.returncode
299  if self.returnedCode != SKIP_RETURN_CODE:
300  logging.debug(
301  f"completed test {self.name} with returncode = {self.returnedCode}"
302  )
303  logging.debug("validating test...")
304  val_start_time = time.perf_counter()
305  self.result, self.causes = self.ValidateOutput(
306  stdout=self.out, stderr=self.err, result=self.result
307  )
308  self.validate_time = round(time.perf_counter() - val_start_time, 2)
309  else:
310  logging.debug(f"skipped test {self.name}")
311  self.status = "skipped"
312 
313  # remove the temporary directory if we created it
314  if self.use_temp_dir and not self._common_tmpdir:
315  shutil.rmtree(workdir, True)
316 
317  os.chdir(self.basedir)
318 
319  if self.status != "skipped":
320  # handle application exit code
321  if self.signal is not None:
322  if int(self.returnedCode) != -int(self.signal):
323  self.causes.append("exit code")
324 
325  elif self.exit_code is not None:
326  if int(self.returnedCode) != int(self.exit_code):
327  self.causes.append("exit code")
328 
329  elif self.returnedCode != 0:
330  self.causes.append("exit code")
331 
332  if self.causes:
333  self.status = "failed"
334  else:
335  self.status = "passed"
336 
337  else:
338  self.status = "skipped"
339 
340  logging.debug("%s: %s", self.name, self.status)
341  field_mapping = {
342  "Exit Code": "returnedCode",
343  "stderr": "err",
344  "Arguments": "args",
345  "Runtime Environment": "environment",
346  "Status": "status",
347  "stdout": "out",
348  "Program Name": "program",
349  "Name": "name",
350  "Validator": "validator",
351  "Validation execution time": "validate_time",
352  "Output Reference File": "reference",
353  "Error Reference File": "error_reference",
354  "Causes": "causes",
355  # 'Validator Result': 'result.annotations',
356  "Unsupported Platforms": "unsupported_platforms",
357  "Stack Trace": "stack_trace",
358  }
359  resultDict = [
360  (key, getattr(self, attr))
361  for key, attr in field_mapping.items()
362  if getattr(self, attr)
363  ]
364  resultDict.append(
365  (
366  "Working Directory",
367  RationalizePath(os.path.join(os.getcwd(), self.workdir)),
368  )
369  )
370  # print(dict(resultDict).keys())
371  resultDict.extend(self.result.annotations.items())
372  # print(self.result.annotations.keys())
373  resultDict = dict(resultDict)
374 
375  # Special cases
376  if "Validator" in resultDict:
377  resultDict["Validator"] = (
378  '<pre><code class="language-{}">{}</code></pre>'.format(
379  "python", escape_for_html(resultDict["Validator"])
380  )
381  )
382  return resultDict
383 
384  # -------------------------------------------------#
385  # ----------------Validating tool------------------#
386  # -------------------------------------------------#
387 
388  def ValidateOutput(self, stdout, stderr, result):
389  if not self.stderr:
390  self.validateWithReference(stdout, stderr, result, self.causes)
391  elif stderr.strip() != self.stderr.strip():
392  self.causes.append("standard error")
393  return result, self.causes
394 
396  self,
397  reference=None,
398  stdout=None,
399  result=None,
400  causes=None,
401  signature_offset=0,
402  signature=None,
403  id=None,
404  ):
405  """
406  Given a block of text, tries to find it in the output. The block had to be identified by a signature line. By default, the first line is used as signature, or the line pointed to by signature_offset. If signature_offset points outside the block, a signature line can be passed as signature argument. Note: if 'signature' is None (the default), a negative signature_offset is interpreted as index in a list (e.g. -1 means the last line), otherwise the it is interpreted as the number of lines before the first one of the block the signature must appear. The parameter 'id' allow to distinguish between different calls to this function in the same validation code.
407  """
408 
409  if reference is None:
410  reference = self.reference
411  if stdout is None:
412  stdout = self.out
413  if result is None:
414  result = self.result
415  if causes is None:
416  causes = self.causes
417 
418  reflines = list(filter(None, map(lambda s: s.rstrip(), reference.splitlines())))
419  if not reflines:
420  raise RuntimeError("Empty (or null) reference")
421  # the same on standard output
422  outlines = list(filter(None, map(lambda s: s.rstrip(), stdout.splitlines())))
423 
424  res_field = "GaudiTest.RefBlock"
425  if id:
426  res_field += "_%s" % id
427 
428  if signature is None:
429  if signature_offset < 0:
430  signature_offset = len(reference) + signature_offset
431  signature = reflines[signature_offset]
432  # find the reference block in the output file
433  try:
434  pos = outlines.index(signature)
435  outlines = outlines[
436  pos - signature_offset : pos + len(reflines) - signature_offset
437  ]
438  if reflines != outlines:
439  msg = "standard output"
440  # I do not want 2 messages in causes if the function is called
441  # twice
442  if msg not in causes:
443  causes.append(msg)
444  result[res_field + ".observed"] = result.Quote("\n".join(outlines))
445  except ValueError:
446  causes.append("missing signature")
447  result[res_field + ".signature"] = result.Quote(signature)
448  if len(reflines) > 1 or signature != reflines[0]:
449  result[res_field + ".expected"] = result.Quote("\n".join(reflines))
450  return causes
451 
453  self, expected={"ERROR": 0, "FATAL": 0}, stdout=None, result=None, causes=None
454  ):
455  """
456  Count the number of messages with required severity (by default ERROR and FATAL)
457  and check if their numbers match the expected ones (0 by default).
458  The dictionary "expected" can be used to tune the number of errors and fatals
459  allowed, or to limit the number of expected warnings etc.
460  """
461 
462  if stdout is None:
463  stdout = self.out
464  if result is None:
465  result = self.result
466  if causes is None:
467  causes = self.causes
468 
469  # prepare the dictionary to record the extracted lines
470  errors = {}
471  for sev in expected:
472  errors[sev] = []
473 
474  outlines = stdout.splitlines()
475  from math import log10
476 
477  fmt = "%%%dd - %%s" % (int(log10(len(outlines) + 1)))
478 
479  linecount = 0
480  for l in outlines:
481  linecount += 1
482  words = l.split()
483  if len(words) >= 2 and words[1] in errors:
484  errors[words[1]].append(fmt % (linecount, l.rstrip()))
485 
486  for e in errors:
487  if len(errors[e]) != expected[e]:
488  causes.append("%s(%d)" % (e, len(errors[e])))
489  result["GaudiTest.lines.%s" % e] = result.Quote("\n".join(errors[e]))
490  result["GaudiTest.lines.%s.expected#" % e] = result.Quote(
491  str(expected[e])
492  )
493 
494  return causes
495 
497  self,
498  stdout=None,
499  result=None,
500  causes=None,
501  trees_dict=None,
502  ignore=r"Basket|.*size|Compression",
503  ):
504  """
505  Compare the TTree summaries in stdout with the ones in trees_dict or in
506  the reference file. By default ignore the size, compression and basket
507  fields.
508  The presence of TTree summaries when none is expected is not a failure.
509  """
510  if stdout is None:
511  stdout = self.out
512  if result is None:
513  result = self.result
514  if causes is None:
515  causes = self.causes
516  if trees_dict is None:
517  lreference = self._expandReferenceFileName(self.reference)
518  # call the validator if the file exists
519  if lreference and os.path.isfile(lreference):
520  trees_dict = findTTreeSummaries(open(lreference).read())
521  else:
522  trees_dict = {}
523 
524  from pprint import PrettyPrinter
525 
526  pp = PrettyPrinter()
527  if trees_dict:
528  result["GaudiTest.TTrees.expected"] = result.Quote(pp.pformat(trees_dict))
529  if ignore:
530  result["GaudiTest.TTrees.ignore"] = result.Quote(ignore)
531 
532  trees = findTTreeSummaries(stdout)
533  failed = cmpTreesDicts(trees_dict, trees, ignore)
534  if failed:
535  causes.append("trees summaries")
536  msg = "%s: %s != %s" % getCmpFailingValues(trees_dict, trees, failed)
537  result["GaudiTest.TTrees.failure_on"] = result.Quote(msg)
538  result["GaudiTest.TTrees.found"] = result.Quote(pp.pformat(trees))
539 
540  return causes
541 
543  self, stdout=None, result=None, causes=None, dict=None, ignore=None
544  ):
545  """
546  Compare the TTree summaries in stdout with the ones in trees_dict or in
547  the reference file. By default ignore the size, compression and basket
548  fields.
549  The presence of TTree summaries when none is expected is not a failure.
550  """
551  if stdout is None:
552  stdout = self.out
553  if result is None:
554  result = self.result
555  if causes is None:
556  causes = self.causes
557 
558  if dict is None:
559  lreference = self._expandReferenceFileName(self.reference)
560  # call the validator if the file exists
561  if lreference and os.path.isfile(lreference):
562  dict = findHistosSummaries(open(lreference).read())
563  else:
564  dict = {}
565 
566  from pprint import PrettyPrinter
567 
568  pp = PrettyPrinter()
569  if dict:
570  result["GaudiTest.Histos.expected"] = result.Quote(pp.pformat(dict))
571  if ignore:
572  result["GaudiTest.Histos.ignore"] = result.Quote(ignore)
573 
574  histos = findHistosSummaries(stdout)
575  failed = cmpTreesDicts(dict, histos, ignore)
576  if failed:
577  causes.append("histos summaries")
578  msg = "%s: %s != %s" % getCmpFailingValues(dict, histos, failed)
579  result["GaudiTest.Histos.failure_on"] = result.Quote(msg)
580  result["GaudiTest.Histos.found"] = result.Quote(pp.pformat(histos))
581 
582  return causes
583 
585  self, stdout=None, stderr=None, result=None, causes=None, preproc=None
586  ):
587  """
588  Default validation acti*on: compare standard output and error to the
589  reference files.
590  """
591 
592  if stdout is None:
593  stdout = self.out
594  if stderr is None:
595  stderr = self.err
596  if result is None:
597  result = self.result
598  if causes is None:
599  causes = self.causes
600 
601  # set the default output preprocessor
602  if preproc is None:
603  preproc = normalizeTestSuite
604  # check standard output
605  lreference = self._expandReferenceFileName(self.reference)
606  # call the validator if the file exists
607  if lreference and os.path.isfile(lreference):
608  causes += ReferenceFileValidator(
609  lreference, "standard output", "Output Diff", preproc=preproc
610  )(stdout, result)
611  elif lreference:
612  causes += ["missing reference file"]
613  # Compare TTree summaries
614  causes = self.CheckTTreesSummaries(stdout, result, causes)
615  causes = self.CheckHistosSummaries(stdout, result, causes)
616  if causes and lreference: # Write a new reference file for stdout
617  try:
618  cnt = 0
619  newrefname = ".".join([lreference, "new"])
620  while os.path.exists(newrefname):
621  cnt += 1
622  newrefname = ".".join([lreference, "~%d~" % cnt, "new"])
623  newref = open(newrefname, "w")
624  # sanitize newlines
625  for l in stdout.splitlines():
626  newref.write(l.rstrip() + "\n")
627  del newref # flush and close
628  result["New Output Reference File"] = os.path.relpath(
629  newrefname, self.basedir
630  )
631  except IOError:
632  # Ignore IO errors when trying to update reference files
633  # because we may be in a read-only filesystem
634  pass
635 
636  # check standard error
637  lreference = self._expandReferenceFileName(self.error_reference)
638  # call the validator if we have a file to use
639  if lreference:
640  if os.path.isfile(lreference):
641  newcauses = ReferenceFileValidator(
642  lreference, "standard error", "Error Diff", preproc=preproc
643  )(stderr, result)
644  else:
645  newcauses = ["missing error reference file"]
646  causes += newcauses
647  if newcauses and lreference: # Write a new reference file for stdedd
648  cnt = 0
649  newrefname = ".".join([lreference, "new"])
650  while os.path.exists(newrefname):
651  cnt += 1
652  newrefname = ".".join([lreference, "~%d~" % cnt, "new"])
653  newref = open(newrefname, "w")
654  # sanitize newlines
655  for l in stderr.splitlines():
656  newref.write(l.rstrip() + "\n")
657  del newref # flush and close
658  result["New Error Reference File"] = os.path.relpath(
659  newrefname, self.basedir
660  )
661  else:
662  causes += BasicOutputValidator(
663  lreference, "standard error", "ExecTest.expected_stderr"
664  )(stderr, result)
665  return causes
666 
668  self,
669  output_file,
670  reference_file,
671  result=None,
672  causes=None,
673  detailed=True,
674  ):
675  """
676  JSON validation action: compare json file to reference file
677  """
678 
679  if result is None:
680  result = self.result
681  if causes is None:
682  causes = self.causes
683 
684  if not os.path.isfile(output_file):
685  causes.append(f"output file {output_file} does not exist")
686  return causes
687 
688  try:
689  with open(output_file) as f:
690  output = json.load(f)
691  except json.JSONDecodeError as err:
692  causes.append("json parser error")
693  result["output_parse_error"] = f"json parser error in {output_file}: {err}"
694  return causes
695 
696  lreference = self._expandReferenceFileName(reference_file)
697  if not lreference:
698  causes.append("reference file not set")
699  elif not os.path.isfile(lreference):
700  causes.append("reference file does not exist")
701  else:
702  causes += JSONOutputValidator()(lreference, output, result, detailed)
703  if causes and lreference: # Write a new reference file for output
704  try:
705  cnt = 0
706  newrefname = ".".join([lreference, "new"])
707  while os.path.exists(newrefname):
708  cnt += 1
709  newrefname = ".".join([lreference, "~%d~" % cnt, "new"])
710  with open(newrefname, "w") as newref:
711  json.dump(output, newref, indent=4)
712  result["New JSON Output Reference File"] = os.path.relpath(
713  newrefname, self.basedir
714  )
715  except IOError:
716  # Ignore IO errors when trying to update reference files
717  # because we may be in a read-only filesystem
718  pass
719  return causes
720 
721  def _expandReferenceFileName(self, reffile):
722  # if no file is passed, do nothing
723  if not reffile:
724  return ""
725 
726  # function to split an extension in constituents parts
727  import re
728 
729  def platformSplit(p):
730  return set(re.split(r"[-+]", p))
731 
732  reference = os.path.normpath(
733  os.path.join(self.basedir, os.path.expandvars(reffile))
734  )
735 
736  # old-style platform-specific reference name
737  spec_ref = reference[:-3] + GetPlatform(self)[0:3] + reference[-3:]
738  if os.path.isfile(spec_ref):
739  reference = spec_ref
740  else: # look for new-style platform specific reference files:
741  # get all the files whose name start with the reference filename
742  dirname, basename = os.path.split(reference)
743  if not dirname:
744  dirname = "."
745  head = basename + "."
746  head_len = len(head)
747  platform = platformSplit(GetPlatform(self))
748  if "do0" in platform:
749  platform.add("dbg")
750  candidates = []
751  for f in os.listdir(dirname):
752  if f.startswith(head):
753  req_plat = platformSplit(f[head_len:])
754  if platform.issuperset(req_plat):
755  candidates.append((len(req_plat), f))
756  if candidates: # take the one with highest matching
757  # FIXME: it is not possible to say if x86_64-slc5-gcc43-dbg
758  # has to use ref.x86_64-gcc43 or ref.slc5-dbg
759  candidates.sort()
760  reference = os.path.join(dirname, candidates[-1][1])
761  return reference
762 
763 
764 # ======= GAUDI TOOLS =======
765 
766 import difflib
767 import shutil
768 
769 try:
770  from GaudiKernel import ROOT6WorkAroundEnabled
771 except ImportError:
772 
774  # dummy implementation
775  return False
776 
777 
778 # --------------------------------- TOOLS ---------------------------------#
779 
780 
782  """
783  Function used to normalize the used path
784  """
785  newPath = os.path.normpath(os.path.expandvars(p))
786  if os.path.exists(newPath):
787  p = os.path.realpath(newPath)
788  return p
789 
790 
791 def which(executable):
792  """
793  Locates an executable in the executables path ($PATH) and returns the full
794  path to it. An application is looked for with or without the '.exe' suffix.
795  If the executable cannot be found, None is returned
796  """
797  if os.path.isabs(executable):
798  if not os.path.isfile(executable):
799  if executable.endswith(".exe"):
800  if os.path.isfile(executable[:-4]):
801  return executable[:-4]
802  else:
803  executable = os.path.split(executable)[1]
804  else:
805  return executable
806  for d in os.environ.get("PATH").split(os.pathsep):
807  fullpath = os.path.join(d, executable)
808  if os.path.isfile(fullpath):
809  return fullpath
810  elif executable.endswith(".exe") and os.path.isfile(fullpath[:-4]):
811  return fullpath[:-4]
812  return None
813 
814 
815 # -------------------------------------------------------------------------#
816 # ----------------------------- Result Classe -----------------------------#
817 # -------------------------------------------------------------------------#
818 
819 
820 class Result:
821  PASS = "PASS"
822  FAIL = "FAIL"
823  ERROR = "ERROR"
824  UNTESTED = "UNTESTED"
825 
826  EXCEPTION = ""
827  RESOURCE = ""
828  TARGET = ""
829  TRACEBACK = ""
830  START_TIME = ""
831  END_TIME = ""
832  TIMEOUT_DETAIL = ""
833 
834  def __init__(self, kind=None, id=None, outcome=PASS, annotations={}):
835  self.annotations = annotations.copy()
836 
837  def __getitem__(self, key):
838  assert isinstance(key, str)
839  return self.annotations[key]
840 
841  def __setitem__(self, key, value):
842  assert isinstance(key, str)
843  assert isinstance(value, str), "{!r} is not a string".format(value)
844  self.annotations[key] = value
845 
846  def Quote(self, text):
847  """
848  Convert text to html by escaping special chars and adding <pre> tags.
849  """
850  return "<pre>{}</pre>".format(escape_for_html(text))
851 
852 
853 # -------------------------------------------------------------------------#
854 # --------------------------- Validator Classes ---------------------------#
855 # -------------------------------------------------------------------------#
856 
857 # Basic implementation of an option validator for Gaudi test. This
858 # implementation is based on the standard (LCG) validation functions used
859 # in QMTest.
860 
861 
863  def __init__(self, ref, cause, result_key):
864  self.ref = ref
865  self.cause = cause
866  self.result_key = result_key
867 
868  def __call__(self, out, result):
869  """Validate the output of the program.
870  'stdout' -- A string containing the data written to the standard output
871  stream.
872  'stderr' -- A string containing the data written to the standard error
873  stream.
874  'result' -- A 'Result' object. It may be used to annotate
875  the outcome according to the content of stderr.
876  returns -- A list of strings giving causes of failure."""
877 
878  causes = []
879  # Check the output
880  if not self.__CompareText(out, self.ref):
881  causes.append(self.cause)
882  result[self.result_key] = result.Quote(self.ref)
883 
884  return causes
885 
886  def __CompareText(self, s1, s2):
887  """Compare 's1' and 's2', ignoring line endings.
888  's1' -- A string.
889  's2' -- A string.
890  returns -- True if 's1' and 's2' are the same, ignoring
891  differences in line endings."""
892  if ROOT6WorkAroundEnabled("ReadRootmapCheck"):
893  # FIXME: (MCl) Hide warnings from new rootmap sanity check until we
894  # can fix them
895  to_ignore = re.compile(
896  r"Warning in <TInterpreter::ReadRootmapFile>: .* is already in .*"
897  )
898 
899  def keep_line(l):
900  return not to_ignore.match(l)
901 
902  return list(filter(keep_line, s1.splitlines())) == list(
903  filter(keep_line, s2.splitlines())
904  )
905  else:
906  return s1.splitlines() == s2.splitlines()
907 
908 
909 # ------------------------ Preprocessor elements ------------------------#
911  """Base class for a callable that takes a file and returns a modified
912  version of it."""
913 
914  def __processLine__(self, line):
915  return line
916 
917  def __processFile__(self, lines):
918  output = []
919  for l in lines:
920  l = self.__processLine__(l)
921  if l:
922  output.append(l)
923  return output
924 
925  def __call__(self, input):
926  if not isinstance(input, str):
927  lines = input
928  mergeback = False
929  else:
930  lines = input.splitlines()
931  mergeback = True
932  output = self.__processFile__(lines)
933  if mergeback:
934  output = "\n".join(output)
935  return output
936 
937  def __add__(self, rhs):
938  return FilePreprocessorSequence([self, rhs])
939 
940 
942  def __init__(self, members=[]):
943  self.members = members
944 
945  def __add__(self, rhs):
946  return FilePreprocessorSequence(self.members + [rhs])
947 
948  def __call__(self, input):
949  output = input
950  for pp in self.members:
951  output = pp(output)
952  return output
953 
954 
956  def __init__(self, strings=[], regexps=[]):
957  import re
958 
959  self.strings = strings
960  self.regexps = list(map(re.compile, regexps))
961 
962  def __processLine__(self, line):
963  for s in self.strings:
964  if line.find(s) >= 0:
965  return None
966  for r in self.regexps:
967  if r.search(line):
968  return None
969  return line
970 
971 
973  def __init__(self, start, end):
974  self.start = start
975  self.end = end
976  self._skipping = False
977 
978  def __processLine__(self, line):
979  if self.start in line:
980  self._skipping = True
981  return None
982  elif self.end in line:
983  self._skipping = False
984  elif self._skipping:
985  return None
986  return line
987 
988 
990  def __init__(self, orig, repl="", when=None):
991  if when:
992  when = re.compile(when)
993  self._operations = [(when, re.compile(orig), repl)]
994 
995  def __add__(self, rhs):
996  if isinstance(rhs, RegexpReplacer):
997  res = RegexpReplacer("", "", None)
998  res._operations = self._operations + rhs._operations
999  else:
1000  res = FilePreprocessor.__add__(self, rhs)
1001  return res
1002 
1003  def __processLine__(self, line):
1004  for w, o, r in self._operations:
1005  if w is None or w.search(line):
1006  line = o.sub(r, line)
1007  return line
1008 
1009 
1010 # Common preprocessors
1011 maskPointers = RegexpReplacer("0x[0-9a-fA-F]{4,16}", "0x########")
1012 normalizeDate = RegexpReplacer(
1013  "[0-2]?[0-9]:[0-5][0-9]:[0-5][0-9] [0-9]{4}[-/][01][0-9][-/][0-3][0-9][ A-Z]*",
1014  "00:00:00 1970-01-01",
1015 )
1016 normalizeEOL = FilePreprocessor()
1017 normalizeEOL.__processLine__ = lambda line: str(line).rstrip() + "\n"
1018 
1019 skipEmptyLines = FilePreprocessor()
1020 # FIXME: that's ugly
1021 skipEmptyLines.__processLine__ = lambda line: (line.strip() and line) or None
1022 
1023 # Special preprocessor sorting the list of strings (whitespace separated)
1024 # that follow a signature on a single line
1025 
1026 
1028  def __init__(self, signature):
1029  self.signature = signature
1030  self.siglen = len(signature)
1031 
1032  def __processLine__(self, line):
1033  pos = line.find(self.signature)
1034  if pos >= 0:
1035  line = line[: (pos + self.siglen)]
1036  lst = line[(pos + self.siglen) :].split()
1037  lst.sort()
1038  line += " ".join(lst)
1039  return line
1040 
1041 
1043  """
1044  Sort group of lines matching a regular expression
1045  """
1046 
1047  def __init__(self, exp):
1048  self.exp = exp if hasattr(exp, "match") else re.compile(exp)
1049 
1050  def __processFile__(self, lines):
1051  match = self.exp.match
1052  output = []
1053  group = []
1054  for l in lines:
1055  if match(l):
1056  group.append(l)
1057  else:
1058  if group:
1059  group.sort()
1060  output.extend(group)
1061  group = []
1062  output.append(l)
1063  return output
1064 
1065 
1066 # Preprocessors for GaudiTestSuite
1067 normalizeTestSuite = maskPointers + normalizeDate
1068 for w, o, r in [
1069  ("TIMER", r"\s+[+-]?[0-9]+[0-9.e+-]*", " 0"), # Normalize time output
1070  ("release all pending", r"^.*/([^/]*:.*)", r"\1"),
1071  ("^#.*file", r"file '.*[/\\]([^/\\]*)$", r"file '\1"),
1072  (
1073  "^JobOptionsSvc.*options successfully read in from",
1074  r"read in from .*[/\\]([^/\\]*)$",
1075  r"file \1",
1076  ), # normalize path to options
1077  # Normalize UUID, except those ending with all 0s (i.e. the class IDs)
1078  (
1079  None,
1080  r"[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}(?!-0{12})-[0-9A-Fa-f]{12}",
1081  "00000000-0000-0000-0000-000000000000",
1082  ),
1083  # Absorb a change in ServiceLocatorHelper
1084  (
1085  "ServiceLocatorHelper::",
1086  "ServiceLocatorHelper::(create|locate)Service",
1087  "ServiceLocatorHelper::service",
1088  ),
1089  # Remove the leading 0 in Windows' exponential format
1090  (None, r"e([-+])0([0-9][0-9])", r"e\1\2"),
1091  # Output line changed in Gaudi v24
1092  (None, r"Service reference count check:", r"Looping over all active services..."),
1093  # Ignore count of declared properties (anyway they are all printed)
1094  (
1095  None,
1096  r"^(.*(DEBUG|SUCCESS) List of ALL properties of .*#properties = )\d+",
1097  r"\1NN",
1098  ),
1099  ("ApplicationMgr", r"(declareMultiSvcType|addMultiSvc): ", ""),
1100  (r"Property \['Name': Value\]", r"( = '[^']+':)'(.*)'", r"\1\2"),
1101  ("TimelineSvc", "to file 'TimelineFile':", "to file "),
1102  ("DataObjectHandleBase", r'DataObjectHandleBase\‍("([^"]*)"\‍)', r"'\1'"),
1103  # Output line changes in Gaudi v38r3
1104  (
1105  "Added successfully Conversion service:",
1106  "Added successfully Conversion service:",
1107  "Added successfully Conversion service ",
1108  ),
1109 ]:
1110  normalizeTestSuite += RegexpReplacer(o, r, w)
1111 
1112 lineSkipper = LineSkipper(
1113  [
1114  "//GP:",
1115  "JobOptionsSvc INFO # ",
1116  "JobOptionsSvc WARNING # ",
1117  "Time User",
1118  "Welcome to",
1119  "This machine has a speed",
1120  "running on",
1121  "ToolSvc.Sequenc... INFO",
1122  "DataListenerSvc INFO XML written to file:",
1123  "[INFO]",
1124  "[WARNING]",
1125  "DEBUG No writable file catalog found which contains FID:",
1126  "DEBUG Service base class initialized successfully",
1127  # changed between v20 and v21
1128  "DEBUG Incident timing:",
1129  # introduced with patch #3487
1130  # changed the level of the message from INFO to
1131  # DEBUG
1132  "INFO 'CnvServices':[",
1133  # message removed because could be printed in constructor
1134  "DEBUG 'CnvServices':[",
1135  # The signal handler complains about SIGXCPU not
1136  # defined on some platforms
1137  "SIGXCPU",
1138  # Message removed with redesing of JobOptionsSvc
1139  "ServiceLocatorHelper::service: found service JobOptionsSvc",
1140  # Ignore warnings for properties case mismatch
1141  "mismatching case for property name:",
1142  # Message demoted to DEBUG in gaudi/Gaudi!992
1143  "Histograms saving not required.",
1144  # Message added in gaudi/Gaudi!577
1145  "Properties are dumped into",
1146  # Messages changed in gaudi/Gaudi!1426
1147  "WARNING no ROOT output file name",
1148  "INFO Writing ROOT histograms to:",
1149  "INFO Completed update of ROOT histograms in:",
1150  # absorb changes in data dependencies reports (https://gitlab.cern.ch/gaudi/Gaudi/-/merge_requests/1348)
1151  "Data Deps for ",
1152  "data dependencies:",
1153  ],
1154  regexps=[
1155  r"^JobOptionsSvc INFO *$",
1156  r"^# ", # Ignore python comments
1157  # skip the message reporting the version of the root file
1158  r"(Always|SUCCESS)\s*(Root f|[^ ]* F)ile version:",
1159  r"File '.*.xml' does not exist",
1160  r"INFO Refer to dataset .* by its file ID:",
1161  r"INFO Referring to dataset .* by its file ID:",
1162  r"INFO Disconnect from dataset",
1163  r"INFO Disconnected from dataset",
1164  r"INFO Disconnected data IO:",
1165  r"IncidentSvc\s*(DEBUG (Adding|Removing)|VERBOSE Calling)",
1166  # Ignore StatusCodeSvc related messages
1167  r".*StatusCodeSvc.*",
1168  r".*StatusCodeCheck.*",
1169  r"Num\s*\|\s*Function\s*\|\s*Source Library",
1170  r"^[-+]*\s*$",
1171  # Hide the fake error message coming from POOL/ROOT (ROOT 5.21)
1172  r"ERROR Failed to modify file: .* Errno=2 No such file or directory",
1173  # Hide unchecked StatusCodes from dictionaries
1174  r"^ +[0-9]+ \|.*ROOT",
1175  r"^ +[0-9]+ \|.*\|.*Dict",
1176  # Hide EventLoopMgr total timing report
1177  r"EventLoopMgr.*---> Loop Finished",
1178  r"HiveSlimEventLo.*---> Loop Finished",
1179  # Remove ROOT TTree summary table, which changes from one version to the
1180  # other
1181  r"^\*.*\*$",
1182  # Remove Histos Summaries
1183  r"SUCCESS\s*Booked \d+ Histogram\‍(s\‍)",
1184  r"^ \|",
1185  r"^ ID=",
1186  # Ignore added/removed properties
1187  r"Property(.*)'Audit(Algorithm|Tool|Service)s':",
1188  r"Property(.*)'Audit(Begin|End)Run':",
1189  # these were missing in tools
1190  r"Property(.*)'AuditRe(start|initialize)':",
1191  r"Property(.*)'Blocking':",
1192  # removed with gaudi/Gaudi!273
1193  r"Property(.*)'ErrorCount(er)?':",
1194  # added with gaudi/Gaudi!306
1195  r"Property(.*)'Sequential':",
1196  # added with gaudi/Gaudi!314
1197  r"Property(.*)'FilterCircularDependencies':",
1198  # removed with gaudi/Gaudi!316
1199  r"Property(.*)'IsClonable':",
1200  # ignore uninteresting/obsolete messages
1201  r"Property update for OutputLevel : new value =",
1202  r"EventLoopMgr\s*DEBUG Creating OutputStream",
1203  r".*StalledEventMonitoring.*",
1204  ],
1205 )
1206 
1207 if ROOT6WorkAroundEnabled("ReadRootmapCheck"):
1208  # FIXME: (MCl) Hide warnings from new rootmap sanity check until we can
1209  # fix them
1210  lineSkipper += LineSkipper(
1211  regexps=[
1212  r"Warning in <TInterpreter::ReadRootmapFile>: .* is already in .*",
1213  ]
1214  )
1215 
1216 normalizeTestSuite = (
1217  lineSkipper
1218  + normalizeTestSuite
1219  + skipEmptyLines
1220  + normalizeEOL
1221  + LineSorter("Services to release : ")
1222  + SortGroupOfLines(r"^\S+\s+(DEBUG|SUCCESS) Property \[\'Name\':")
1223 )
1224 # for backward compatibility
1225 normalizeExamples = normalizeTestSuite
1226 
1227 # --------------------- Validation functions/classes ---------------------#
1228 
1229 
1231  def __init__(self, reffile, cause, result_key, preproc=normalizeTestSuite):
1232  self.reffile = os.path.expandvars(reffile)
1233  self.cause = cause
1234  self.result_key = result_key
1235  self.preproc = preproc
1236 
1237  def __call__(self, stdout, result):
1238  causes = []
1239  if os.path.isfile(self.reffile):
1240  orig = open(self.reffile).readlines()
1241  if self.preproc:
1242  orig = self.preproc(orig)
1243  result[self.result_key + ".preproc.orig"] = result.Quote(
1244  "\n".join(map(str.strip, orig))
1245  )
1246  else:
1247  orig = []
1248  new = stdout.splitlines()
1249  if self.preproc:
1250  new = self.preproc(new)
1251 
1252  # Note: we have to make sure that we do not have `\n` in the comparison
1253  filterdiffs = list(
1254  difflib.unified_diff(
1255  [l.rstrip() for l in orig],
1256  [l.rstrip() for l in new],
1257  n=1,
1258  fromfile="Reference file",
1259  tofile="Actual output",
1260  lineterm="",
1261  )
1262  )
1263  if filterdiffs:
1264  result[self.result_key] = result.Quote("\n".join(filterdiffs))
1265  result[self.result_key + ".preproc.new"] = result.Quote(
1266  "\n".join(map(str.strip, new))
1267  )
1268  causes.append(self.cause)
1269  return causes
1270 
1271 
1273  """
1274  Scan stdout to find ROOT TTree summaries and digest them.
1275  """
1276  stars = re.compile(r"^\*+$")
1277  outlines = stdout.splitlines()
1278  nlines = len(outlines)
1279  trees = {}
1280 
1281  i = 0
1282  while i < nlines: # loop over the output
1283  # look for
1284  while i < nlines and not stars.match(outlines[i]):
1285  i += 1
1286  if i < nlines:
1287  tree, i = _parseTTreeSummary(outlines, i)
1288  if tree:
1289  trees[tree["Name"]] = tree
1290 
1291  return trees
1292 
1293 
1294 def cmpTreesDicts(reference, to_check, ignore=None):
1295  """
1296  Check that all the keys in reference are in to_check too, with the same value.
1297  If the value is a dict, the function is called recursively. to_check can
1298  contain more keys than reference, that will not be tested.
1299  The function returns at the first difference found.
1300  """
1301  fail_keys = []
1302  # filter the keys in the reference dictionary
1303  if ignore:
1304  ignore_re = re.compile(ignore)
1305  keys = [key for key in reference if not ignore_re.match(key)]
1306  else:
1307  keys = reference.keys()
1308  # loop over the keys (not ignored) in the reference dictionary
1309  for k in keys:
1310  if k in to_check: # the key must be in the dictionary to_check
1311  if isinstance(reference[k], dict) and isinstance(to_check[k], dict):
1312  # if both reference and to_check values are dictionaries,
1313  # recurse
1314  failed = fail_keys = cmpTreesDicts(reference[k], to_check[k], ignore)
1315  else:
1316  # compare the two values
1317  failed = to_check[k] != reference[k]
1318  else: # handle missing keys in the dictionary to check (i.e. failure)
1319  to_check[k] = None
1320  failed = True
1321  if failed:
1322  fail_keys.insert(0, k)
1323  break # exit from the loop at the first failure
1324  return fail_keys # return the list of keys bringing to the different values
1325 
1326 
1327 def getCmpFailingValues(reference, to_check, fail_path):
1328  c = to_check
1329  r = reference
1330  for k in fail_path:
1331  c = c.get(k, None)
1332  r = r.get(k, None)
1333  if c is None or r is None:
1334  break # one of the dictionaries is not deep enough
1335  return (fail_path, r, c)
1336 
1337 
1338 # signature of the print-out of the histograms
1339 h_count_re = re.compile(r"^(.*)SUCCESS\s+Booked (\d+) Histogram\‍(s\‍) :\s+([\s\w=-]*)")
1340 
1341 
1342 def _parseTTreeSummary(lines, pos):
1343  """
1344  Parse the TTree summary table in lines, starting from pos.
1345  Returns a tuple with the dictionary with the digested informations and the
1346  position of the first line after the summary.
1347  """
1348  result = {}
1349  i = pos + 1 # first line is a sequence of '*'
1350  count = len(lines)
1351 
1352  def splitcols(l):
1353  return [f.strip() for f in l.strip("*\n").split(":", 2)]
1354 
1355  def parseblock(ll):
1356  r = {}
1357  delta_i = 0
1358  cols = splitcols(ll[0])
1359 
1360  if len(ll) == 3:
1361  # default one line name/title
1362  r["Name"], r["Title"] = cols[1:]
1363  elif len(ll) == 4:
1364  # in case title is moved to next line due to too long name
1365  delta_i = 1
1366  r["Name"] = cols[1]
1367  r["Title"] = ll[1].strip("*\n").split("|")[1].strip()
1368  else:
1369  assert False
1370 
1371  cols = splitcols(ll[1 + delta_i])
1372  r["Entries"] = int(cols[1])
1373 
1374  sizes = cols[2].split()
1375  r["Total size"] = int(sizes[2])
1376  if sizes[-1] == "memory":
1377  r["File size"] = 0
1378  else:
1379  r["File size"] = int(sizes[-1])
1380 
1381  cols = splitcols(ll[2 + delta_i])
1382  sizes = cols[2].split()
1383  if cols[0] == "Baskets":
1384  r["Baskets"] = int(cols[1])
1385  r["Basket size"] = int(sizes[2])
1386  r["Compression"] = float(sizes[-1])
1387 
1388  return r
1389 
1390  def nextblock(lines, i):
1391  delta_i = 1
1392  dots = re.compile(r"^\.+$")
1393  stars = re.compile(r"^\*+$")
1394  count = len(lines)
1395  while (
1396  i + delta_i < count
1397  and not dots.match(lines[i + delta_i][1:-1])
1398  and not stars.match(lines[i + delta_i])
1399  ):
1400  delta_i += 1
1401  return i + delta_i
1402 
1403  if i < (count - 3) and lines[i].startswith("*Tree"):
1404  i_nextblock = nextblock(lines, i)
1405  result = parseblock(lines[i:i_nextblock])
1406  result["Branches"] = {}
1407  i = i_nextblock + 1
1408  while i < (count - 3) and lines[i].startswith("*Br"):
1409  if i < (count - 2) and lines[i].startswith("*Branch "):
1410  # skip branch header
1411  i += 3
1412  continue
1413  i_nextblock = nextblock(lines, i)
1414  if i_nextblock >= count:
1415  break
1416  branch = parseblock(lines[i:i_nextblock])
1417  result["Branches"][branch["Name"]] = branch
1418  i = i_nextblock + 1
1419 
1420  return (result, i)
1421 
1422 
1423 def parseHistosSummary(lines, pos):
1424  """
1425  Extract the histograms infos from the lines starting at pos.
1426  Returns the position of the first line after the summary block.
1427  """
1428  global h_count_re
1429  h_table_head = re.compile(
1430  r'SUCCESS\s+(1D|2D|3D|1D profile|2D profile) histograms in directory\s+"(\w*)"'
1431  )
1432  h_short_summ = re.compile(r"ID=([^\"]+)\s+\"([^\"]+)\"\s+(.*)")
1433 
1434  nlines = len(lines)
1435 
1436  # decode header
1437  m = h_count_re.search(lines[pos])
1438  name = m.group(1).strip()
1439  total = int(m.group(2))
1440  header = {}
1441  for k, v in [x.split("=") for x in m.group(3).split()]:
1442  header[k] = int(v)
1443  pos += 1
1444  header["Total"] = total
1445 
1446  summ = {}
1447  while pos < nlines:
1448  m = h_table_head.search(lines[pos])
1449  if m:
1450  t, d = m.groups(1) # type and directory
1451  t = t.replace(" profile", "Prof")
1452  pos += 1
1453  if pos < nlines:
1454  l = lines[pos]
1455  else:
1456  l = ""
1457  cont = {}
1458  if l.startswith(" | ID"):
1459  # table format
1460  titles = [x.strip() for x in l.split("|")][1:]
1461  pos += 1
1462  while pos < nlines and lines[pos].startswith(" |"):
1463  l = lines[pos]
1464  values = [x.strip() for x in l.split("|")][1:]
1465  hcont = {}
1466  for i in range(len(titles)):
1467  hcont[titles[i]] = values[i]
1468  cont[hcont["ID"]] = hcont
1469  pos += 1
1470  elif l.startswith(" ID="):
1471  while pos < nlines and lines[pos].startswith(" ID="):
1472  values = [
1473  x.strip() for x in h_short_summ.search(lines[pos]).groups()
1474  ]
1475  cont[values[0]] = values
1476  pos += 1
1477  else: # not interpreted
1478  raise RuntimeError("Cannot understand line %d: '%s'" % (pos, l))
1479  if d not in summ:
1480  summ[d] = {}
1481  summ[d][t] = cont
1482  summ[d]["header"] = header
1483  else:
1484  break
1485  if not summ:
1486  # If the full table is not present, we use only the header
1487  summ[name] = {"header": header}
1488  return summ, pos
1489 
1490 
1492  """
1493  Scan stdout to find ROOT TTree summaries and digest them.
1494  """
1495  outlines = stdout.splitlines()
1496  nlines = len(outlines) - 1
1497  summaries = {}
1498  global h_count_re
1499 
1500  pos = 0
1501  while pos < nlines:
1502  summ = {}
1503  # find first line of block:
1504  match = h_count_re.search(outlines[pos])
1505  while pos < nlines and not match:
1506  pos += 1
1507  match = h_count_re.search(outlines[pos])
1508  if match:
1509  summ, pos = parseHistosSummary(outlines, pos)
1510  summaries.update(summ)
1511  return summaries
1512 
1513 
1514 def GetPlatform(self):
1515  """
1516  Return the platform Id defined in CMTCONFIG or SCRAM_ARCH.
1517  """
1518  arch = "None"
1519  # check architecture name
1520  if "BINARY_TAG" in os.environ:
1521  arch = os.environ["BINARY_TAG"]
1522  elif "CMTCONFIG" in os.environ:
1523  arch = os.environ["CMTCONFIG"]
1524  elif "SCRAM_ARCH" in os.environ:
1525  arch = os.environ["SCRAM_ARCH"]
1526  elif os.environ.get("ENV_CMAKE_BUILD_TYPE", "") in (
1527  "Debug",
1528  "FastDebug",
1529  "Developer",
1530  ):
1531  arch = "dummy-dbg"
1532  elif os.environ.get("ENV_CMAKE_BUILD_TYPE", "") in (
1533  "Release",
1534  "MinSizeRel",
1535  "RelWithDebInfo",
1536  "",
1537  ): # RelWithDebInfo == -O2 -g -DNDEBUG
1538  arch = "dummy-opt"
1539  return arch
1540 
1541 
1542 def isWinPlatform(self):
1543  """
1544  Return True if the current platform is Windows.
1545 
1546  This function was needed because of the change in the CMTCONFIG format,
1547  from win32_vc71_dbg to i686-winxp-vc9-dbg.
1548  """
1549  platform = GetPlatform(self)
1550  return "winxp" in platform or platform.startswith("win")
1551 
1552 
1554  def __call__(self, ref, out, result, detailed=True):
1555  """Validate JSON output.
1556  returns -- A list of strings giving causes of failure."""
1557 
1558  causes = []
1559  try:
1560  with open(ref) as f:
1561  expected = json.load(f)
1562  except json.JSONDecodeError as err:
1563  causes.append("json parser error")
1564  result["reference_parse_error"] = f"json parser error in {ref}: {err}"
1565  return causes
1566 
1567  if not detailed:
1568  if expected != out:
1569  causes.append("json content")
1570  result["json_diff"] = "detailed diff was turned off"
1571  return causes
1572 
1573  # piggyback on TestCase dict diff report
1574  t = TestCase()
1575  # sort both lists (these are list of entities) as the order is not supposed to matter
1576  # indeed, the JSONSink implementation does not garantee any particular order
1577  # but as JSON does not have sets, we get back a sorted list here
1578  expected = sorted(expected, key=lambda item: (item["component"], item["name"]))
1579  out = sorted(out, key=lambda item: (item["component"], item["name"]))
1580  try:
1581  t.assertEqual(expected, out)
1582  except AssertionError as err:
1583  causes.append("json content")
1584  result["json_diff"] = str(err).splitlines()[0]
1585 
1586  return causes
GaudiTesting.BaseTest.ReferenceFileValidator.reffile
reffile
Definition: BaseTest.py:1232
GaudiTesting.BaseTest.BaseTest.causes
causes
Definition: BaseTest.py:122
GaudiTesting.BaseTest.SortGroupOfLines.__init__
def __init__(self, exp)
Definition: BaseTest.py:1047
GaudiTesting.BaseTest.BaseTest.options
options
Definition: BaseTest.py:110
GaudiTesting.BaseTest.FilePreprocessor
Definition: BaseTest.py:910
MSG::hex
MsgStream & hex(MsgStream &log)
Definition: MsgStream.h:282
GaudiTesting.BaseTest.Result.__getitem__
def __getitem__(self, key)
Definition: BaseTest.py:837
GaudiTesting.BaseTest.BasicOutputValidator.ref
ref
Definition: BaseTest.py:864
GaudiTesting.BaseTest.dumpProcs
def dumpProcs(name)
Definition: BaseTest.py:67
GaudiTesting.BaseTest.LineSorter.siglen
siglen
Definition: BaseTest.py:1030
GaudiTesting.BaseTest.FilePreprocessor.__call__
def __call__(self, input)
Definition: BaseTest.py:925
GaudiTesting.BaseTest.LineSorter
Definition: BaseTest.py:1027
GaudiTesting.BaseTest._parseTTreeSummary
def _parseTTreeSummary(lines, pos)
Definition: BaseTest.py:1342
GaudiTesting.BaseTest.LineSorter.__processLine__
def __processLine__(self, line)
Definition: BaseTest.py:1032
GaudiTesting.BaseTest.BaseTest.out
out
Definition: BaseTest.py:125
GaudiTesting.BaseTest.BaseTest.CheckHistosSummaries
def CheckHistosSummaries(self, stdout=None, result=None, causes=None, dict=None, ignore=None)
Definition: BaseTest.py:542
GaudiTesting.BaseTest.sanitize_for_xml
def sanitize_for_xml(data)
Definition: BaseTest.py:50
GaudiTesting.BaseTest.BaseTest._common_tmpdir
_common_tmpdir
Definition: BaseTest.py:103
GaudiTesting.BaseTest.BaseTest.reference
reference
Definition: BaseTest.py:108
GaudiTesting.BaseTest.BasicOutputValidator.__init__
def __init__(self, ref, cause, result_key)
Definition: BaseTest.py:863
GaudiTesting.BaseTest.BaseTest.timeout
timeout
Definition: BaseTest.py:112
GaudiTesting.BaseTest.ReferenceFileValidator.preproc
preproc
Definition: BaseTest.py:1235
GaudiTesting.BaseTest.BaseTest.validateWithReference
def validateWithReference(self, stdout=None, stderr=None, result=None, causes=None, preproc=None)
Definition: BaseTest.py:584
GaudiTesting.BaseTest.getCmpFailingValues
def getCmpFailingValues(reference, to_check, fail_path)
Definition: BaseTest.py:1327
GaudiPartProp.decorators.get
get
decorate the vector of properties
Definition: decorators.py:283
GaudiTesting.BaseTest.BasicOutputValidator.result_key
result_key
Definition: BaseTest.py:866
GaudiTesting.BaseTest.BaseTest.proc
proc
Definition: BaseTest.py:127
GaudiTesting.BaseTest._new_backslashreplace_errors
def _new_backslashreplace_errors(exc)
Definition: BaseTest.py:32
GaudiTesting.BaseTest.BaseTest.stack_trace
stack_trace
Definition: BaseTest.py:128
GaudiTesting.BaseTest.FilePreprocessor.__processFile__
def __processFile__(self, lines)
Definition: BaseTest.py:917
GaudiTesting.BaseTest.BaseTest.environment
environment
Definition: BaseTest.py:114
GaudiTesting.BaseTest.LineSorter.signature
signature
Definition: BaseTest.py:1029
GaudiTesting.BaseTest.BaseTest.exit_code
exit_code
Definition: BaseTest.py:113
GaudiTesting.BaseTest.BlockSkipper.start
start
Definition: BaseTest.py:974
GaudiTesting.BaseTest.kill_tree
def kill_tree(ppid, sig)
Definition: BaseTest.py:77
GaudiTesting.BaseTest.Result.Quote
def Quote(self, text)
Definition: BaseTest.py:846
GaudiTesting.BaseTest.FilePreprocessorSequence.__add__
def __add__(self, rhs)
Definition: BaseTest.py:945
Containers::map
struct GAUDI_API map
Parametrisation class for map-like implementation.
Definition: KeyedObjectManager.h:35
GaudiTesting.BaseTest.BaseTest.validateJSONWithReference
def validateJSONWithReference(self, output_file, reference_file, result=None, causes=None, detailed=True)
Definition: BaseTest.py:667
GaudiTesting.BaseTest.FilePreprocessorSequence
Definition: BaseTest.py:941
GaudiTesting.BaseTest.BaseTest.__init__
def __init__(self)
Definition: BaseTest.py:105
GaudiTesting.BaseTest.RegexpReplacer._operations
_operations
Definition: BaseTest.py:993
GaudiTesting.BaseTest.BaseTest.err
err
Definition: BaseTest.py:126
compareOutputFiles.target
target
Definition: compareOutputFiles.py:489
GaudiTesting.BaseTest.SortGroupOfLines.__processFile__
def __processFile__(self, lines)
Definition: BaseTest.py:1050
GaudiTesting.BaseTest.BlockSkipper
Definition: BaseTest.py:972
GaudiTesting.BaseTest.BaseTest.args
args
Definition: BaseTest.py:107
GaudiTesting.BaseTest.BaseTest.result
result
Definition: BaseTest.py:123
GaudiTesting.BaseTest.FilePreprocessor.__processLine__
def __processLine__(self, line)
Definition: BaseTest.py:914
GaudiTesting.BaseTest.FilePreprocessorSequence.__call__
def __call__(self, input)
Definition: BaseTest.py:948
GaudiTesting.BaseTest.BaseTest.workdir
workdir
Definition: BaseTest.py:117
GaudiTesting.BaseTest.BlockSkipper._skipping
_skipping
Definition: BaseTest.py:976
GaudiTesting.BaseTest.ReferenceFileValidator.cause
cause
Definition: BaseTest.py:1233
GaudiTesting.BaseTest.parseHistosSummary
def parseHistosSummary(lines, pos)
Definition: BaseTest.py:1423
GaudiTesting.BaseTest.BaseTest.validate_time
validate_time
Definition: BaseTest.py:130
GaudiTesting.BaseTest.RegexpReplacer
Definition: BaseTest.py:989
GaudiTesting.BaseTest.isWinPlatform
def isWinPlatform(self)
Definition: BaseTest.py:1542
GaudiTesting.BaseTest.LineSkipper.regexps
regexps
Definition: BaseTest.py:960
GaudiTesting.BaseTest.BaseTest.basedir
basedir
Definition: BaseTest.py:129
GaudiTesting.BaseTest.which
def which(executable)
Definition: BaseTest.py:791
GaudiTesting.BaseTest.SortGroupOfLines.exp
exp
Definition: BaseTest.py:1048
GaudiTesting.BaseTest.BaseTest.unsupported_platforms
unsupported_platforms
Definition: BaseTest.py:115
GaudiTesting.BaseTest.Result.__init__
def __init__(self, kind=None, id=None, outcome=PASS, annotations={})
Definition: BaseTest.py:834
GaudiTesting.BaseTest.BlockSkipper.end
end
Definition: BaseTest.py:975
GaudiTesting.BaseTest.BaseTest.returnedCode
returnedCode
Definition: BaseTest.py:124
GaudiTesting.BaseTest.LineSkipper.strings
strings
Definition: BaseTest.py:959
GaudiTesting.BaseTest.BasicOutputValidator.__call__
def __call__(self, out, result)
Definition: BaseTest.py:868
GaudiTesting.BaseTest.cmpTreesDicts
def cmpTreesDicts(reference, to_check, ignore=None)
Definition: BaseTest.py:1294
GaudiTesting.BaseTest.Result.annotations
annotations
Definition: BaseTest.py:835
GaudiTesting.BaseTest.BaseTest.name
name
Definition: BaseTest.py:121
format
GAUDI_API std::string format(const char *,...)
MsgStream format utility "a la sprintf(...)".
Definition: MsgStream.cpp:119
GaudiTesting.BaseTest.JSONOutputValidator
Definition: BaseTest.py:1553
GaudiTesting.BaseTest.RegexpReplacer.__processLine__
def __processLine__(self, line)
Definition: BaseTest.py:1003
GaudiTesting.BaseTest.FilePreprocessorSequence.members
members
Definition: BaseTest.py:943
GaudiTesting.BaseTest.BaseTest._expandReferenceFileName
def _expandReferenceFileName(self, reffile)
Definition: BaseTest.py:721
GaudiTesting.BaseTest.BaseTest.signal
signal
Definition: BaseTest.py:116
GaudiTesting.BaseTest.SortGroupOfLines
Definition: BaseTest.py:1042
GaudiTesting.BaseTest.BaseTest.findReferenceBlock
def findReferenceBlock(self, reference=None, stdout=None, result=None, causes=None, signature_offset=0, signature=None, id=None)
Definition: BaseTest.py:395
GaudiTesting.BaseTest.ReferenceFileValidator.__init__
def __init__(self, reffile, cause, result_key, preproc=normalizeTestSuite)
Definition: BaseTest.py:1231
GaudiTesting.BaseTest.RationalizePath
def RationalizePath(p)
Definition: BaseTest.py:781
GaudiTesting.BaseTest.LineSkipper
Definition: BaseTest.py:955
GaudiTesting.BaseTest.ReferenceFileValidator
Definition: BaseTest.py:1230
hivetimeline.read
def read(f, regex=".*", skipevents=0)
Definition: hivetimeline.py:32
GaudiTesting.BaseTest.BaseTest.program
program
Definition: BaseTest.py:106
GaudiTesting.BaseTest.FilePreprocessorSequence.__init__
def __init__(self, members=[])
Definition: BaseTest.py:942
GaudiTesting.BaseTest.ReferenceFileValidator.__call__
def __call__(self, stdout, result)
Definition: BaseTest.py:1237
GaudiTesting.BaseTest.BasicOutputValidator.cause
cause
Definition: BaseTest.py:865
GaudiTesting.BaseTest.FilePreprocessor.__add__
def __add__(self, rhs)
Definition: BaseTest.py:937
GaudiTesting.BaseTest.ReferenceFileValidator.result_key
result_key
Definition: BaseTest.py:1234
GaudiTesting.BaseTest.BlockSkipper.__init__
def __init__(self, start, end)
Definition: BaseTest.py:973
GaudiTesting.BaseTest.RegexpReplacer.__init__
def __init__(self, orig, repl="", when=None)
Definition: BaseTest.py:990
GaudiTesting.BaseTest.findHistosSummaries
def findHistosSummaries(stdout)
Definition: BaseTest.py:1491
GaudiTesting.BaseTest.Result.__setitem__
def __setitem__(self, key, value)
Definition: BaseTest.py:841
GaudiTesting.BaseTest.BaseTest.CheckTTreesSummaries
def CheckTTreesSummaries(self, stdout=None, result=None, causes=None, trees_dict=None, ignore=r"Basket|.*size|Compression")
Definition: BaseTest.py:496
GaudiTesting.BaseTest.BaseTest
Definition: BaseTest.py:102
GaudiTesting.BaseTest.BaseTest.countErrorLines
def countErrorLines(self, expected={"ERROR":0, "FATAL":0}, stdout=None, result=None, causes=None)
Definition: BaseTest.py:452
GaudiTesting.BaseTest.BaseTest.error_reference
error_reference
Definition: BaseTest.py:109
GaudiTesting.BaseTest.BaseTest.ValidateOutput
def ValidateOutput(self, stdout, stderr, result)
Definition: BaseTest.py:388
GaudiTesting.BaseTest.JSONOutputValidator.__call__
def __call__(self, ref, out, result, detailed=True)
Definition: BaseTest.py:1554
GaudiTesting.BaseTest.BasicOutputValidator
Definition: BaseTest.py:862
GaudiTesting.BaseTest.LineSkipper.__init__
def __init__(self, strings=[], regexps=[])
Definition: BaseTest.py:956
GaudiTesting.BaseTest.Result
Definition: BaseTest.py:820
GaudiTesting.BaseTest.BaseTest.run
def run(self)
Definition: BaseTest.py:132
GaudiTesting.BaseTest.findTTreeSummaries
def findTTreeSummaries(stdout)
Definition: BaseTest.py:1272
GaudiTesting.BaseTest.BasicOutputValidator.__CompareText
def __CompareText(self, s1, s2)
Definition: BaseTest.py:886
GaudiTesting.BaseTest.RegexpReplacer.__add__
def __add__(self, rhs)
Definition: BaseTest.py:995
compareOutputFiles.pp
pp
Definition: compareOutputFiles.py:507
GaudiTesting.BaseTest.BaseTest.stderr
stderr
Definition: BaseTest.py:111
GaudiTesting.BaseTest.LineSorter.__init__
def __init__(self, signature)
Definition: BaseTest.py:1028
GaudiTesting.BaseTest.LineSkipper.__processLine__
def __processLine__(self, line)
Definition: BaseTest.py:962
GaudiTesting.BaseTest.ROOT6WorkAroundEnabled
def ROOT6WorkAroundEnabled(id=None)
Definition: BaseTest.py:773
GaudiTesting.BaseTest.BaseTest.use_temp_dir
use_temp_dir
Definition: BaseTest.py:118
GaudiTesting.BaseTest.GetPlatform
def GetPlatform(self)
Definition: BaseTest.py:1514
GaudiTesting.BaseTest.BaseTest.status
status
Definition: BaseTest.py:120
Gaudi::Functional::details::zip::range
decltype(auto) range(Args &&... args)
Zips multiple containers together to form a single range.
Definition: details.h:98
GaudiTesting.BaseTest.BlockSkipper.__processLine__
def __processLine__(self, line)
Definition: BaseTest.py:978