Belle II Software light-2406-ragdoll
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
17
18
19class ExamplesTest(unittest.TestCase):
20 """Test to run all example scripts."""
21
22 @unittest.skipIf(not os.getenv('BELLE2_EXAMPLES_DATA_DIR'),
23 "$BELLE2_EXAMPLES_DATA_DIR not found.")
24 @unittest.skipIf(not os.getenv('BELLE2_VALIDATION_DATA_DIR'),
25 "$BELLE2_VALIDATION_DATA_DIR not found.")
26 def _test_examples_dir(self, path_to_glob, broken=None):
27 """
28 Internal function to test a directory full of example scripts with an optional list of broken scripts to be skipped.
29
30 Parameters:
31 path_to_glob (str): the path to search for scripts
32 broken (list(str)): (optional) scripts that are known to be broken and can be skipped
33 """
34 if broken is None:
35 broken = []
36 all_egs = sorted(glob.glob(find_file(path_to_glob) + "/*.py"))
37 for eg in all_egs:
38 filename = os.path.basename(eg)
39 if filename not in broken:
40 with self.subTest(msg=filename):
41 result = subprocess.run(['basf2', '-n1', eg], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)
42 if result.returncode != 0:
43 # failure running example so let's print the output
44 # on stderr so it's not split from output of unittest
45 # done like this since we don't want to decode/encode utf8
46 sys.stdout.buffer.write(result.stdout)
47 self.assertEqual(result.returncode, 0)
48
49
50def scanTTree(filename):
51 from ROOT import TFile
52
53 tfile = TFile(filename, "READ")
54 print(f"TFile: {filename}")
55
56 # get lists of TTree in the filename
57 ttrees = [key.GetName() for key in tfile.GetListOfKeys() if key.GetClassName() == "TTree"]
58
59 for ttree_name in ttrees:
60 print(f"TTree: {ttree_name}")
61
62 # get TTree object
63 ttree = tfile.Get(ttree_name)
64 num_entries = ttree.GetEntries()
65
66 if num_entries == 0:
67 print("No entry found")
68 # print name all TBranches in the TTree
69 for branch in ttree.GetListOfBranches():
70 branch_name = branch.GetName()
71 print(f"TBranch: {branch_name}")
72
73 else:
74 ttree.GetEntry(0)
75 # print name and value of all TBranches in the TTree
76 for branch in ttree.GetListOfBranches():
77 branch_name = branch.GetName()
78 branch_value = getattr(ttree, branch_name)
79
80 if isinstance(branch_value, float):
81 print(f"TBranch: {branch_name}, {branch_value:.4g}")
82 else:
83 print(f"TBranch: {branch_name}, {branch_value}")
84
85 tfile.Close()
def _test_examples_dir(self, path_to_glob, broken=None)