Belle II Software  release-06-01-15
test_skim_definitions.py
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 
4 
11 
12 """
13 Tests to enforce rules about how skims are defined.
14 """
15 
16 import ast
17 import inspect
18 import unittest
19 
20 from skim.registry import Registry
21 
22 
23 class TestSkimRules(unittest.TestCase):
25  """
26  Check that no skims use ma.applyEventCuts anywhere. BaseSkim.skim_event_cuts is
27  preferred, since ma.applyEventCuts is incompatible with CombinedSkim.
28  """
29  SkimsWithApplyEventCuts = set()
30 
31  for skim in Registry.names:
32  classdef = Registry.get_skim_function(skim)
33  source = inspect.getsource(classdef)
34  tree = ast.parse(source)
35 
36  for node in ast.walk(tree):
37  # Search for calls to applyEventCuts
38  if not isinstance(node, ast.Call):
39  continue
40 
41  # Handle two cases: `applyEventCuts` and `ma.applyEventCuts`
42  try:
43  function = node.func.id
44  except AttributeError:
45  function = node.func.attr
46 
47  if function == "applyEventCuts":
48  SkimsWithApplyEventCuts.add(skim)
49 
50  if SkimsWithApplyEventCuts:
51  plural = len(SkimsWithApplyEventCuts) > 1
52  self.fail(
53  f"The following skim{plural*'s'} use{(not plural)*'s'} "
54  "modularAnalysis.applyEventCuts, which cannot be used in skims: "
55  f"{', '.join(SkimsWithApplyEventCuts)}. Please use "
56  "BaseSkim.skim_event_cuts instead."
57  )
58 
59 
60 if __name__ == "__main__":
61  unittest.main()