Belle II Software development
b2test_utils_analysis.py
1#!/usr/bin/env python3
2
3
10
11import os
12import sys
13import subprocess
14import unittest
15import glob
16from basf2 import find_file
17from b2test_utils import configure_logging_for_tests
18
19
20class ExamplesTest(unittest.TestCase):
21 """Test to run all example scripts."""
22
23 @unittest.skipIf(not os.getenv('BELLE2_EXAMPLES_DATA_DIR'),
24 "$BELLE2_EXAMPLES_DATA_DIR not found.")
25 @unittest.skipIf(not os.getenv('BELLE2_VALIDATION_DATA_DIR'),
26 "$BELLE2_VALIDATION_DATA_DIR not found.")
27 def _test_examples_dir(self, path_to_glob, broken=None, filepattern="", nevents=10):
28 """
29 Internal function to test a directory full of example scripts with an optional list of broken scripts to be skipped.
30
31 Parameters:
32 path_to_glob (str): the path to search for scripts
33 broken (list(str)): (optional) scripts that are known to be broken and can be skipped
34 """
35 if broken is None:
36 broken = []
37 configure_logging_for_tests()
38 all_egs = sorted(glob.glob(find_file(path_to_glob) + f"/{filepattern}*.py"))
39 for eg in all_egs:
40 filename = os.path.basename(eg)
41 if filename not in broken:
42 with self.subTest(msg=filename):
43 outputfilename = filename.replace('.py', '.root')
44 result = subprocess.run(['basf2', '-n', f'{nevents}', eg, '-o',
45 outputfilename], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
46 if result.returncode != 0:
47 # failure running example so let's print the output
48 # on stderr so it's not split from output of unittest
49 # done like this since we don't want to decode/encode utf8
50 sys.stdout.buffer.write(result.stdout)
51 self.assertEqual(result.returncode, 0)
52
53 if os.path.exists(outputfilename) and isNtuple(outputfilename):
54 scanTTree(outputfilename)
55
56
57def scanTTree(filename):
58 from ROOT import TFile
59
60 tfile = TFile(filename, "READ")
61 print(f"TFile: {filename}")
62
63 # get lists of TTree in the filename
64 ttrees = [key.GetName() for key in tfile.GetListOfKeys() if key.GetClassName() == "TTree"]
65
66 for ttree_name in ttrees:
67 if ttree_name == "persistent":
68 continue
69 print(f"TTree: {ttree_name}")
70
71 # get TTree object
72 ttree = tfile.Get(ttree_name)
73 num_entries = ttree.GetEntries()
74
75 if num_entries == 0:
76 print("No entry found")
77 # print name all TBranches in the TTree
78 for branch in ttree.GetListOfBranches():
79 branch_name = branch.GetName()
80 print(f"TBranch: {branch_name}")
81
82 else:
83 ttree.GetEntry(0)
84 # print name and value of all TBranches in the TTree
85 for branch in ttree.GetListOfBranches():
86 branch_name = branch.GetName()
87 branch_value = getattr(ttree, branch_name)
88
89 if isinstance(branch_value, float):
90 print(f"TBranch: {branch_name}, {branch_value:.4g}")
91 else:
92 print(f"TBranch: {branch_name}, {branch_value}")
93
94 tfile.Close()
95
96
97def isNtuple(filename):
98 from ROOT import Belle2, TFile
99
100 tfile = TFile(filename, "READ")
101 ttree = tfile.Get("persistent")
102 if not ttree:
103 return False
104 ttree.GetEntry(0)
105
106 metadata = Belle2.FileMetaData(ttree.FileMetaData)
107
108 return metadata.getDataDescription()["isNtupleMetaData"]
Metadata information about a file.
Definition: FileMetaData.h:29
def _test_examples_dir(self, path_to_glob, broken=None, filepattern="", nevents=10)