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