Belle II Software  release-06-01-15
awesome_examples.py
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 
4 
11 
12 """
13 Test all the examples of the awesome package.
14 Proudly based on analysis/test/examples.py.
15 """
16 
17 # std
18 import os
19 import sys
20 import subprocess
21 import unittest
22 import glob
23 
24 # basf2
25 from basf2 import find_file
26 from b2test_utils import clean_working_directory
27 
28 
29 def light_release() -> bool:
30  """ Returns true if we're in a light release """
31  try:
32  import generators # noqa
33  except ModuleNotFoundError:
34  return True
35  return False
36 
37 
38 class AwesomeExamplesTest(unittest.TestCase):
39  """ Test our awesome examples. """
40 
42  self,
43  path_to_glob: str
44  ):
45  """
46  Internal function to test a directory full of example scripts.
47 
48  Parameters:
49  path_to_glob (str): the path to a directory to search for python
50  scripts.
51  """
52  # Do not run the test if we are in a light release.
53  if light_release():
54  return
55  working_dir = find_file(path_to_glob)
56  examples = sorted(glob.glob(f'{working_dir}/*.py'))
57  for example in examples:
58  filename = os.path.basename(example)
59  with self.subTest(msg=filename):
60  result = subprocess.run(
61  ["basf2", "-n1", example],
62  stdout=subprocess.PIPE,
63  stderr=subprocess.STDOUT,
64  )
65  if result.returncode != 0:
66  # failure running example so let's print the output
67  # on stderr so it's not split from output of unittest
68  # done like this since we don't want to decode/encode utf8
69  sys.stdout.buffer.write(result.stdout)
70  self.assertEqual(result.returncode, 0)
71 
72  def test_examples(self):
73  """Run the examples of the awesome package. """
74 
75  self._test_examples_dir_test_examples_dir(
76  path_to_glob='online_book/awesome/examples',
77  )
78 
79 
80 if __name__ == "__main__":
81  with clean_working_directory():
82  unittest.main()
def _test_examples_dir(self, str path_to_glob)