Belle II Software  release-05-02-19
findFile.py
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3 
4 from basf2 import find_file, B2INFO
5 import os
6 
7 # define shortcut for getting symlink-free path
8 rl = os.path.realpath
9 
10 
11 def expect_missing(*args):
12  """Return true if passing the arguments to find_file raises a FileNotFoundError, otherwise False"""
13  # raises a file not found exception if not found (unless supressed)
14  try:
15  find_file(*args)
16  except FileNotFoundError:
17  return True
18  else:
19  return False
20 
21 
22 assert expect_missing('framework/tests/ThisFileDoesntExist')
23 # try to find TEST data file
24 assert expect_missing('findFile.py', 'test')
25 
26 B2INFO("No more output from here...")
27 assert '' == find_file('framework/tests/ThisFileDoesntExist', silent=True)
28 
29 # find ourselves relative to basf2 dir
30 abspath = rl(find_file('framework/tests/findFile.py'))
31 assert len(abspath) > 0
32 
33 # adding '/' is ok, but optional
34 assert abspath == rl(find_file('/framework/tests/findFile.py'))
35 
36 # absolute paths should be found
37 assert abspath == rl(find_file(abspath))
38 
39 # also works on directories
40 testdir = rl(find_file('/framework/tests/'))
41 assert len(testdir) > 0
42 
43 # paths relative to PWD are also ok (no, prefixing this with / is not allowed)
44 os.chdir(testdir)
45 assert abspath == rl(find_file('findFile.py'))
46 assert abspath == rl(find_file('./findFile.py'))
47 
48 # try finding relative to basf2 dir again (from different location)
49 os.chdir('/')
50 assert abspath == rl(find_file('framework/tests/findFile.py'))
51 assert abspath == rl(find_file('/framework/tests/findFile.py'))
52 assert abspath == rl(find_file('./framework/tests/findFile.py'))
53 
54 # set BELLe2_TEST_DATA_DIR and try to find data file
55 os.environ['BELLE2_TEST_DATA_DIR'] = os.environ.get('BELLE2_RELEASE_DIR', os.environ.get('BELLE2_LOCAL_DIR'))
56 assert abspath == rl(find_file('framework/tests/findFile.py', 'test'))