-
Notifications
You must be signed in to change notification settings - Fork 10
/
Copy pathtest.py
557 lines (479 loc) · 17.1 KB
/
test.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
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
from __future__ import (unicode_literals, print_function, division,
absolute_import)
import contextlib
import itertools
import os
import random
import subprocess
import sys
import tempfile
from collections import defaultdict
from os.path import dirname, join
import pytest
import six
from nbformat import v4
import depfinder
from depfinder import cli, main, inspection, parse_file
from depfinder.main import simple_import_search_conda_forge_import_map, simple_import_to_pkg_map
from depfinder.reports import report_conda_forge_names_from_import_map, extract_pkg_from_import, \
recursively_search_for_name, _builtin_modules
try:
import conda_forge_metadata # noqa
HAS_CF_METADATA = True
except ImportError:
HAS_CF_METADATA = False
random.seed(12345)
# Testing spec:
# - targets: dict
# - required: Iterable of library imports that should be found
# - questionable: Iterable of library imports that should be found
# - code: String. Code that will be parsed to look for imports
complex_imports = [
{'targets':
{'questionable': ['atom', 'chemist', 'molecule', 'physicist']},
'code': """
try:
import molecule
except ImportError:
import atom
else:
import chemist
finally:
import physicist"""
},
{'targets': {'required': ['foo'], 'builtin': ['os']},
'code': """
import foo
try:
import os
except ImportError:
# why would you put this in a try block??
pass""",
},
{
"targets": {
"required": [
"toplevel",
"toplevelfrom",
"inside_class",
"inside_class_from",
],
"questionable": [
"function_inside_class",
"function_inside_class_from",
"inside_for",
"inside_for_else",
"inside_function",
"inside_function_from",
"inside_async_function",
"inside_if",
"inside_else",
"inside_while",
"inside_nested_class",
],
"relative": [
"relative_function",
"relative_function_inside_class",
"relative_inside_class",
],
"builtin": ["os", "pprint"],
},
"code": """
from toplevelfrom import some_function
import toplevel
def function():
import inside_function
from inside_function_from import another_function
from .relative_function import random_function
class Class:
import inside_class
from inside_class_from import some_function
from .relative_inside_class import a_third_function
import os
def __init__(self):
import function_inside_class
from function_inside_class_from import some_function
from .relative_function_inside_class import a_third_function
import pprint
# Handle nesting properly. import in a class def should be treated as "required to import",
# unless its inside any of the nodes that would render it questionable. This import _should_
# land in the questionable section, so we want to make sure it does.
if True:
class NestedClass:
import inside_nested_class
# weird edge cases that we want to make sure end up sorted properly. This hits the "ast.While"
for i in []:
import inside_for
else:
import inside_for_else
# import inside an async function. This hits the "ast.AsyncFunctionDef"
async def async_function():
import inside_async_function
# import inside an if block. This hits the "ast.If"
foo = 'cat'
if foo == 'cat':
import inside_if
else:
import inside_else
# import inside an if block. This hits the "ast.While"
while True:
import inside_while
break
""",
},
{
"targets": {"questionable": ["chico", "groucho", "harpo"]},
"code": """
if this:
import groucho
elif that:
import harpo
else:
import chico"""
},
]
simple_imports = [
{'targets': {'required': ['foo']},
'code': 'import foo'},
{'targets': {'required': ['bar', 'foo']},
'code': 'import foo, bar'},
{'targets': {'required': ['numpy']},
'code': 'import numpy'},
{'targets': {'required': ['matplotlib']},
'code': 'from matplotlib import pyplot'},
# Hit the fake packages code block in main.sanitize_deps()
{'targets': {'required': ['numpy']},
'code': 'from numpy import warnings as npwarn'},
]
relative_imports = [
{'targets': {},
'code': 'from . import bar'},
{'targets': {'relative': ['bar']},
'code': 'from .bar import baz'},
{'targets': {'relative': ['bar']},
'code': 'from ..bar import baz'},
]
@pytest.fixture(scope='module')
def using_stdlib_list():
try:
import stdlib_list
return True
except ImportError:
return False
def test_nested_namespace_builtins(using_stdlib_list):
if using_stdlib_list:
expected = {'builtin': ['concurrent.futures']}
else:
expected = {'builtin': ['concurrent']}
code = 'import concurrent.futures'
test_object = Initter({'targets': expected, 'code': code})
imports = main.get_imported_libs(test_object.code)
assert imports.describe() == test_object.targets
class Initter(object):
def __init__(self, artifact):
targets = artifact.get('targets', {})
self.targets = {k: set(v) for k, v in targets.items()}
self.code = artifact['code']
def test_imports():
for simple_import in complex_imports + simple_imports:
test_object = Initter(simple_import)
imports = main.get_imported_libs(test_object.code)
assert imports.describe() == test_object.targets
def test_relative_imports():
for rel in relative_imports:
test_object = Initter(rel)
imports = main.get_imported_libs(test_object.code)
assert imports.describe() == test_object.targets
def test_for_smoke():
"""Do not validate the output of the functions, just make sure that calling
them does not make depfinder blow up
"""
deps = list(main.iterate_over_library('.'))
assert deps is not None
assert str(deps) is not None
assert repr(deps) is not None
# hit the simple api
assert main.simple_import_search('.') is not None
### NOTEBOOK TESTING CODE ###
@contextlib.contextmanager
def write_notebook(cells):
nb = v4.new_notebook()
nb['cells'] = [v4.new_code_cell(code_cell) for code_cell in cells]
fname = tempfile.NamedTemporaryFile(suffix='.ipynb').name
with open(fname, 'w') as f:
f.write(v4.writes(nb))
try:
yield fname
finally:
os.remove(fname)
def test_notebook_remapping():
code = "import mpl_toolkits"
with write_notebook([code]) as fname:
deps = main.notebook_path_to_dependencies(fname, remap=False)
assert {'required': ['mpl_toolkits']} == deps
assert {} == main.notebook_path_to_dependencies(fname)
@pytest.mark.parametrize("import_list_dict", [complex_imports,
simple_imports,
relative_imports])
def tester(import_list_dict, capsys):
# http://nbviewer.ipython.org/gist/fperez/9716279
for import_dict in import_list_dict:
cell_code = [import_dict['code']]
target = import_dict['targets']
with write_notebook(cell_code) as fname:
# parse the notebook!
assert set(target) == set(main.notebook_path_to_dependencies(fname))
# check the notebook cli
_run_cli(path_to_check=fname)
stdout, stderr = capsys.readouterr()
assert set(target) == set(eval(stdout))
def test_multiple_code_cells(capsys):
targets = defaultdict(set)
import_list_dict = complex_imports + relative_imports + simple_imports
# http://nbviewer.ipython.org/gist/fperez/9716279
code_for_cells = []
for import_dict in import_list_dict:
code_for_cells.append(import_dict['code'])
target = import_dict['targets']
for k, v in target.items():
targets[k].update(set(v))
# turn targets into a dict of sorted lists
targets = {k: sorted(list(v)) for k, v in targets.items()}
with write_notebook(code_for_cells) as fname:
# parse the notebook!
assert targets == main.notebook_path_to_dependencies(fname)
# check the notebook cli
_run_cli(path_to_check=fname)
stdout, stderr = capsys.readouterr()
assert targets == eval(stdout)
### CLI TESTING CODE ###
def _process_args(path_to_check, extra_flags):
"""
Parameters
----------
path_to_check : str, optional
Defaults to the directory of the depfinder package
extra_flags : list, optional
List of extra command line flags to pass.
Defaults to passing nothing extra.
"""
if path_to_check is None:
path_to_check = dirname(depfinder.__file__)
if isinstance(extra_flags, six.string_types):
extra_flags = [extra_flags]
if extra_flags is None:
extra_flags = []
return path_to_check, extra_flags
def _subprocess_cli(path_to_check=None, extra_flags=None):
path_to_check, extra_flags = _process_args(path_to_check, extra_flags)
p = subprocess.Popen(
['depfinder', path_to_check] + extra_flags,
env=dict(os.environ),
stderr=subprocess.PIPE,
stdout=subprocess.PIPE
)
stdout, stderr = p.communicate()
returncode = p.returncode
return stdout, stderr, returncode
def _run_cli(path_to_check=None, extra_flags=None):
"""
Helper function to run depfinder in its cli mode
"""
path_to_check, extra_flags = _process_args(path_to_check, extra_flags)
sys.argv = ['depfinder', path_to_check] + extra_flags
cli.cli()
return None
def known_flags():
# option_strings are the things like ['-h', '--help']
# or are empty lists if the action is a positional
flags = [o.option_strings for o in cli._init_parser()._actions]
# drop the empty flags (these are positional arguments only
flags = [flag for flag in flags if flag]
# now flatten the nested list
flags = [flag for flag_twins in flags for flag in flag_twins]
flags.remove('-k')
flags.remove('--key')
flags.remove('--pdb')
flags.remove('--ignore')
flags.remove('--custom-namespaces')
flags.extend(['-k all', '-k required', '-k optional', '-k builtin',
'-k relative'])
return flags
@pytest.fixture(scope="module")
def flags():
yield known_flags()
@pytest.mark.parametrize(
'flags',
itertools.chain(
[random.sample(known_flags(), i) for i in range(1, len(known_flags()))]
)
)
def test_cli_with_random_flags(flags):
"""
More of a fuzz test for depfinder than a unit test.
Parameters
----------
flags : list
Random combination of valid command line flags
"""
out, err, returncode = _subprocess_cli(extra_flags=flags)
if returncode != 0:
# The only thing that I know of that will exit with a nonzero status
# is if you try to combine quiet mode and verbose mode. This handles
# that case
quiet = {'-q', '--quiet'}
verbose = {'-v', '--verbose'}
flags = set(flags)
assert flags & quiet != set() and flags & verbose != set()
return
assert returncode == 0
@pytest.mark.parametrize(
'path, req',
((dirname(depfinder.__file__), None),
(join(dirname(depfinder.__file__), 'main.py'), set()))
)
def test_cli(path, req, capsys):
"""
Test to ensure that the depfinder cli is finding the dependencies in the
source the depfinder package that are listed in the requirements.txt file
"""
main.PACKAGE_NAME = None
old_argv = sys.argv
sys.argv = ['depfinder']
_run_cli(path_to_check=path)
sys.argv = old_argv
# read stdout and stderr with pytest's built-in capturing mechanism
stdout, stderr = capsys.readouterr()
print('stdout\n{}'.format(stdout))
print('stderr\n{}'.format(stderr))
if req is None:
dependencies_file = join(dirname(dirname(depfinder.__file__)),
'requirements.txt')
dependencies = set([dep for dep in open(dependencies_file, 'r').read().split('\n') if not dep.startswith("stdlib")])
else:
dependencies = req
assert dependencies == set(eval(stdout).get('required', set()))
def test_known_fail_cli(tmpdir):
tmpfile = os.path.join(str(tmpdir), 'bad_file.txt')
import this
with open(tmpfile, 'w') as f:
f.write("".join([this.d.get(this.c, this.c) for this.c in this.s]))
with pytest.raises(RuntimeError):
_run_cli(path_to_check=tmpfile)
def test_known_fail_cli2():
with pytest.raises(cli.InvalidSelection):
_run_cli(extra_flags=['-q', '-v'])
@pytest.mark.parametrize(
'path',
(dirname(depfinder.__file__),
join(dirname(depfinder.__file__), 'main.py'))
)
def test_individual_args(path, flags):
for flag in flags:
if flag in ['-h', '--help']:
# skip the help messages since they cause the system to exit
continue
_run_cli(path_to_check=path, extra_flags=[flag])
_run_cli(path_to_check=path, extra_flags=[flag])
def test_fake_packages():
fake_import = "import mpl_toolkits"
imports = main.get_imported_libs(fake_import)
assert imports.describe() == {'required': {'mpl_toolkits'}}
assert main.sanitize_deps(imports.describe()) == {}
def test_get_top_level_import():
name = 'this.that.something'
top_level_name = inspection.get_top_level_import_name(name)
assert top_level_name == 'this'
name = 'google.cloud.storage.something'
top_level_name = inspection.get_top_level_import_name(name)
assert top_level_name == 'google.cloud.storage'
@pytest.mark.skipif(
not HAS_CF_METADATA,
reason="test of optional conda-forge-metadata integration",
)
def test_report_conda_forge_names_from_import_map():
m, f, c = parse_file(join(dirname(depfinder.__file__), 'utils.py'))
report, import_to_pkg = report_conda_forge_names_from_import_map(c.total_imports)
assert report['required'] == {'pyyaml', 'requests'}
@pytest.mark.skipif(
not HAS_CF_METADATA,
reason="test of optional conda-forge-metadata integration",
)
def test_report_conda_forge_names_from_import_map_ignore():
m, f, c = parse_file(join(dirname(depfinder.__file__), 'inspection.py'))
report, import_to_pkg = report_conda_forge_names_from_import_map(
c.total_imports,
ignore=['*insp*'],
)
assert report['required'] == set()
@pytest.mark.skipif(
not HAS_CF_METADATA,
reason="test of optional conda-forge-metadata integration",
)
def test_simple_import_search_conda_forge_import_map():
path_to_source = dirname(depfinder.__file__)
expected_result = sorted(list({"pyyaml", "requests"}))
report = simple_import_search_conda_forge_import_map(path_to_source)
assert report['required'] == expected_result
@pytest.mark.skipif(
not HAS_CF_METADATA,
reason="test of optional conda-forge-metadata integration",
)
@pytest.mark.parametrize('import_name, expected_result', [
('six.moves', 'six'),
# these need special casing elsewhere
# ('win32com.shell', 'pywin32'),
# ('win32com', 'pywin32'),
("scipy.interpolate", "scipy"),
# this comes from cython but doesn't seem to be a real pkg
('refnanny.hi', 'refnanny.hi')
])
def test_extract_pkg_from_import_for_complex_imports(import_name, expected_result):
result, allpkgs = extract_pkg_from_import(import_name)
assert result == expected_result, allpkgs
@pytest.mark.parametrize('import_name, expected_result', [
('six.moves', False),
])
def test_search_for_name(import_name, expected_result):
builtin_name_maybe = recursively_search_for_name(import_name, _builtin_modules)
assert builtin_name_maybe == expected_result
@pytest.mark.skipif(
not HAS_CF_METADATA,
reason="test of optional conda-forge-metadata integration",
)
def test_simple_import_to_pkg_map():
path_to_source = dirname(depfinder.__file__)
import_to_artifact = simple_import_to_pkg_map(path_to_source)
expected_result = {
'builtin': {},
'questionable': {
'stdlib_list': {'stdlib-list'},
'IPython.core.inputsplitter': {'ipython', 'autovizwidget'},
'conda_forge_metadata.autotick_bot': {'conda-forge-metadata'},
'conda_forge_metadata.libcfgraph': {'conda-forge-metadata'},
},
'questionable no match': {},
'required': {
'requests': {
'apache-libcloud',
'arm_pyart',
'autovizwidget',
'dbxfs',
'google-api-core',
'google-cloud-bigquery-storage-core',
'requests'
},
'requests.exceptions': {
'apache-libcloud',
'arm_pyart',
'autovizwidget',
'dbxfs',
'google-api-core',
'google-cloud-bigquery-storage-core',
'requests'
},
'yaml': {'google-cloud-bigquery-storage-core', 'pyyaml', 'rosco'}
},
'required no match': {}
}
assert import_to_artifact == expected_result