Handle exception raised in recursive_finder API (#49590)

User module can contain Indentation errors or syntax errors.
Handle AST exceptions rather than showing traceback while importing such module.

Fixes: #21707

Signed-off-by: Abhijeet Kasurde <akasurde@redhat.com>
This commit is contained in:
Abhijeet Kasurde 2019-01-04 10:33:37 +05:30 committed by GitHub
parent 73ffe683b2
commit bc6cd13874
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
2 changed files with 18 additions and 1 deletions

View file

@ -462,7 +462,10 @@ def recursive_finder(name, data, py_module_names, py_module_cache, zf):
the module its module_utils files needs.
"""
# Parse the module and find the imports of ansible.module_utils
try:
tree = ast.parse(data)
except (SyntaxError, IndentationError) as e:
raise AnsibleError("Unable to import %s due to %s" % (name, e.msg))
finder = ModuleDepFinder()
finder.visit(tree)

View file

@ -112,6 +112,20 @@ class TestRecursiveFinder(object):
assert finder_containers.py_module_cache == {}
assert frozenset(finder_containers.zf.namelist()) == MODULE_UTILS_BASIC_FILES
def test_module_utils_with_syntax_error(self, finder_containers):
name = 'fake_module'
data = b'#!/usr/bin/python\ndef something(:\n pass\n'
with pytest.raises(ansible.errors.AnsibleError) as exec_info:
recursive_finder(name, data, *finder_containers)
assert 'Unable to import fake_module due to invalid syntax' in str(exec_info)
def test_module_utils_with_identation_error(self, finder_containers):
name = 'fake_module'
data = b'#!/usr/bin/python\n def something():\n pass\n'
with pytest.raises(ansible.errors.AnsibleError) as exec_info:
recursive_finder(name, data, *finder_containers)
assert 'Unable to import fake_module due to unexpected indent' in str(exec_info)
def test_from_import_toplevel_package(self, finder_containers, mocker):
if PY2:
module_utils_data = BytesIO(b'# License\ndef do_something():\n pass\n')