-
Notifications
You must be signed in to change notification settings - Fork 240
/
file_utils.py
254 lines (210 loc) · 7.31 KB
/
file_utils.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
"""
Utilities for working with files.
"""
import sys
import os
import importlib
import unittest
from inspect import getmembers, isclass, ismethod, isfunction
from fnmatch import fnmatch
from os.path import join, basename, dirname, isfile, split, splitext, abspath, expanduser
def get_module_path(fpath):
"""
Given a module filename, return its full Python module path.
This includes enclosing packages and is based on existence of ``__init__.py`` files.
Parameters
----------
fpath : str
Pathname of file.
Returns
-------
str or None
Full module path of the given file. Returns None if the file is not part of a package.
"""
fpath = abspath(fpath)
if basename(fpath).startswith('__init__.'):
pnames = []
else:
pnames = [splitext(basename(fpath))[0]]
path = dirname(fpath)
initfile = join(path, '__init__.py')
if not isfile(initfile):
return None
while isfile(initfile):
path, pname = split(path)
pnames.append(pname)
initfile = join(path, '__init__.py')
return '.'.join(pnames[::-1])
def package_iter(start_dir='.', dir_includes=None, dir_excludes=(), file_includes=None,
file_excludes=()):
"""
Iterate over python files in packages (recursively) starting in start_dir.
NOTE: all *_includes and *_excludes are applied to *local* directory and file names.
Parameters
----------
start_dir : str
Starting directory.
dir_includes : iter of str or None
Glob patterns for directory inclusion. Be careful here because dir names are local,
so, for example, if includes=('foo',), then directory 'foo' would be included, but
any subdirectories of 'foo' that were not also named 'foo' would not.
dir_excludes : iter of str
Glob patterns for directory exclusion.
file_includes : iter of str or None
Glob patterns for file inclusion.
file_excludes : iter of str
Glob patterns for file exclusion.
Yields
------
str
Filenames (full path from start_dir).
"""
file_includes = set() if file_includes is None else set(file_includes)
file_includes.add('*.py')
file_excludes = set() if file_excludes is None else set(file_excludes)
file_excludes.update(('_*', 'test_*', 'api.py', 'parallel_api.py'))
dir_excludes = set() if dir_excludes is None else set(dir_excludes)
dir_excludes.update(('test', 'tests'))
for f in files_iter(start_dir, dir_includes=dir_includes, dir_excludes=dir_excludes,
file_includes=file_includes, file_excludes=file_excludes,
package_only=True):
yield f
def files_iter(start_dir='.', dir_includes=None, dir_excludes=(),
file_includes=None, file_excludes=(), package_only=False):
"""
Iterate over files (recursively) starting in start_dir.
NOTE: all *_includes and *_excludes are applied to *local* directory and file names.
Parameters
----------
start_dir : str
Starting directory.
dir_includes : iter of str or None
Glob patterns for directory inclusion. Be careful here because dir names are local,
so, for example, if includes=('foo',), then directory 'foo' would be included, but
any subdirectories of 'foo' that were not also named 'foo' would not.
dir_excludes : iter of str
Glob patterns for directory exclusion.
file_includes : iter of str or None
Glob patterns for file inclusion.
file_excludes : iter of str
Glob patterns for file exclusion.
package_only : bool
If True, only yield files that are contained in a python package.
Yields
------
str
Filenames (full path from start_dir).
"""
for root, dirs, files in os.walk(start_dir):
if package_only and '__init__.py' not in files:
dirs[:] = []
continue
for pat in dir_excludes:
dirs[:] = sorted([d for d in dirs if not fnmatch(d, pat)])
if dir_includes:
incdirs = set()
for pat in dir_includes:
incdirs.update(d for d in dirs if fnmatch(d, pat))
dirs[:] = sorted(incdirs)
for f in files:
for pat in file_excludes:
if fnmatch(f, pat):
break
else:
if file_includes:
for pat in file_includes:
if fnmatch(f, pat):
yield join(root, f)
else:
yield join(root, f)
def _to_filename(spec):
"""
Return the filename part of the given testspec or the full string if the string is a filename.
Parameters
----------
spec : str
The filename or testspec.
Returns
-------
str
The filename.
"""
if ':' in spec and not os.path.isfile(spec):
fname, rest = spec.rsplit(':', 1)
if not fname.endswith('.py'):
try:
mod = importlib.import_module(fname)
return mod.__file__
except ImportError:
return spec
return fname
return spec
def _load_and_exec(script_name, user_args):
"""
Load and exec the given script as __main__.
Parameters
----------
script_name : str
The name of the script to load and exec.
user_args : list of str
Args to be passed to the user script.
"""
if ':' in script_name and not os.path.isfile(script_name):
return _load_and_run_test(script_name)
sys.path.insert(0, os.path.dirname(script_name))
sys.argv[:] = [script_name] + user_args
with open(script_name, 'rb') as fp:
code = compile(fp.read(), script_name, 'exec')
globals_dict = {
'__file__': script_name,
'__name__': '__main__',
'__package__': None,
'__cached__': None,
}
exec(code, globals_dict)
def _load_and_run_test(testspec):
"""
Load and run an individual test function.
Parameters
----------
testspec : str
<fpath_or_modpath>:<testcase>.<method> OR <fpath_or_modpath>:<function>
"""
syspath_save = sys.path[:]
modpath, funcpath = testspec.rsplit(':', 1)
if modpath.endswith('.py'):
modpath = get_module_path(modpath)
sys.path.append('.')
mod = importlib.import_module(modpath)
try:
return _run_test_func(mod, funcpath)
finally:
sys.path = syspath_save
def _run_test_func(mod, funcpath):
"""
Run the given TestCase method or test function in the given module.
Parameters
----------
mod : module
The module where the test resides.
funcpath : str
Either <testcase>.<method_name> or <func_name>.
Returns
-------
object
In the case of a module level function call, returns whatever the function returns.
"""
parts = funcpath.split('.', 1)
if len(parts) == 2:
tcase_name, method_name = parts
testcase = getattr(mod, tcase_name)(methodName=method_name)
setup = getattr(testcase, 'setUp', None)
if setup is not None:
setup()
getattr(testcase, method_name)()
teardown = getattr(testcase, 'tearDown', None)
if teardown:
teardown()
else:
funcname = parts[0]
return getattr(mod, funcname)()