Isolate globals in import sanity test.

pull/59742/head
Matt Clay 5 years ago
parent 0b8354751b
commit ecddbdf0cb

@ -3,6 +3,12 @@
from __future__ import (absolute_import, division, print_function)
__metaclass__ = type
def main():
"""
Main program function used to isolate globals from imported code.
Changes to globals in imported modules on Python 2.7 will overwrite our own globals.
"""
import contextlib
import os
import re
@ -30,17 +36,14 @@ try:
except ImportError:
AnsibleCollectionLoader = None
class ImporterAnsibleModuleException(Exception):
"""Exception thrown during initialization of ImporterAnsibleModule."""
class ImporterAnsibleModule:
"""Replacement for AnsibleModule to support import testing."""
def __init__(self, *args, **kwargs):
raise ImporterAnsibleModuleException()
# stop Ansible module execution during AnsibleModule instantiation
ansible.module_utils.basic.AnsibleModule = ImporterAnsibleModule
# no-op for _load_params since it may be called before instantiating AnsibleModule
@ -48,8 +51,7 @@ ansible.module_utils.basic._load_params = lambda *args, **kwargs: {} # pylint:
# no-op for removed_module since it is called in place of AnsibleModule instantiation
ansible.module_utils.common.removed.removed_module = lambda *args, **kwargs: None
def main():
def run():
"""Main program function."""
base_dir = os.getcwd()
messages = set()
@ -65,7 +67,6 @@ def main():
if messages:
exit(10)
def test_python_module(path, base_dir, messages, ansible_module):
if ansible_module:
# importing modules with __main__ under Python 2.6 exits with status code 1
@ -149,7 +150,6 @@ def test_python_module(path, base_dir, messages, ansible_module):
report_message(error, messages)
class Capture:
"""Captured output and/or exception."""
def __init__(self):
@ -157,7 +157,6 @@ class Capture:
self.stderr = StringIO()
self.warnings = []
def capture_report(path, capture, messages):
"""Report on captured output.
:type path: str
@ -198,7 +197,6 @@ def capture_report(path, capture, messages):
message = '%s:%d:%d: %s: %s' % (filepath, lineno, 0, warning.category.__name__, msg)
report_message(message, messages)
def report_message(message, messages):
"""Report message if not already reported.
:type message: str
@ -208,7 +206,6 @@ def report_message(message, messages):
messages.add(message)
print(message)
@contextlib.contextmanager
def capture_output(capture):
"""Capture sys.stdout and sys.stderr.
@ -229,6 +226,8 @@ def capture_output(capture):
sys.stdout = old_stdout
sys.stderr = old_stderr
run()
if __name__ == '__main__':
main()

Loading…
Cancel
Save